What are Extension Methods?

What are extension methods in .NET?



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


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/


Extension Methods - Simple Explanation

You can add methods to something, even though you don't have access to the original source code. Let's consider an example to explain that point:

Example:

Suppose I have a dog. All dogs – all animals of type dog - do certain things:

  1. Eat
  2. WagsTail
  3. Cries “Woof / Bow / Wang!” etc

The things that a dog can do are all called “methods”. Now let’s suppose the Great Programmer in OO Heaven forgot to add a method to the dog class: FetchNewspaper(). You want to be able to say:

rex.FetchNewspaper(); // or
beethoven.FetchNewspaper(); 

......even though you don't have access to the source code.

How are you doing to get your dog to do that? Your only solution is to to create an “extension method”.

Creating an Extension Method

(Note the “this” keyword in front of the first parameter below):

public static void FetchNewsPaper(this Dog familyDog)
{
     Console.Writeline(“Goes to get newspaper!”)
}

And if you want your dog to get the newspaper simply do this:

Dog freddie_the_family_dog = new Dog();

freddie_the_family_dog.FetchNewspaper();

You can add a method onto a class without having the source code. This can be extremely handy!