What are Extension Methods?

Developer picture Developer · Dec 31, 2008 · Viewed 8.6k times · Source

What are extension methods in .NET?



EDIT: I have posted a follow up question at Usage of Extension Methods

Answer

Andreas Grech picture Andreas Grech · Dec 31, 2008

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.

Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

Reference: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx

Here is a sample of an Extension Method (notice the this keyword infront of the first parameter):

public static bool IsValidEmailAddress(this string s)
{
    Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
    return regex.IsMatch(s);
}

Now, the above method can be called directly from any string, like such:

bool isValid = "[email protected]".IsValidEmailAddress();

The added methods will then also appear in IntelliSense:

alt text
(source: scottgu.com)

As regards a practical use for Extension Methods, you might add new methods to a class without deriving a new class.

Take a look at the following example:

public class Extended {
    public int Sum() {
        return 7+3+2;
    }
}

public static class Extending {
    public static float Average(this Extended extnd) {
        return extnd.Sum() / 3;
    }
}

As you see, the class Extending is adding a method named average to class Extended. To get the average, you call average method, as it belongs to extended class:

Extended ex = new Extended();

Console.WriteLine(ex.average());

Reference: http://aspguy.wordpress.com/2008/07/03/a-practical-use-of-serialization-and-extension-methods-in-c-30/