Extension methods in C# 3.0

July 8, 2008 by C#  

C# 3.0 introduced interesting new functionality, one of them being extension methods, which enables developers to add methods to existing types, without needing to create a new derived type (interfaces, classes, structs)

Extension methods behave much like instance methods, but have a number of limitations they can't for example access private nor protected members of the type they're extending. (I can imagine the logic behind this)

Note the following code example and how its being defined, you need a static class (all members must be static) and the first parameter of the extension method contains the "this" keyword, informing the compiler which type we're extending. (you may add numerous parameters you wish to pass to this method, but the first parameter must always define the type you want to extend)

public static class ExtensionMethods
{
    public static string Reverse(this string value)
    {
        char[] charArray = value.ToCharArray();
        Array.Reverse(charArray);            
        return new string(charArray);
    }
}

Typically (if you did everything right), your extension method should immediately reflect in your IDE (if you're using one), with a little blue arrow.
Extension Method

One can also write overloads to existing methods using extension methods, but cant override existing ones - remember that whenever you're planning to use these methods, the static class containing your extensions, obviously need to be brought in scope with whatever code you're planning to use it with (namespaces etc)

My feelings on this feature, is that its a tool that must only be used if its REALLY needed. (You can open a tin of tuna with a hammer, but there is better ways to do it)

Also if you have access to the source code to a class you need to extend, consider simply adding the method to the class, don't extend it - unless you've got very good reasons.

Imagine the impact of misusing this feature (which is true for most others), having your business logic for example, all over the show extended by extension methods, where you potentially come to the point where functionality gets decentralized, it can most definitely lead to some ugly unmanageable code.

I've noticed an interesting way Microsoft use extension methods in context with Linq - as soon as you include System.Linq (among others) as a namespace, a number of extension methods gets added, which enables developers to query those types with linq.


Leave a Comment