What are 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:
(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:
- Eat
- WagsTail
- 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!
Extension methods are ways for developers to "add on" methods to objects they can't control.
For instance, if you wanted to add a "DoSomething()" method to the System.Windows.Forms object, since you don't have access to that code, you would simply create an extension method for the form with the following syntax.
Public Module MyExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Sub DoSomething(ByVal source As System.Windows.Forms.Form)
'Do Something
End Sub
End Module
Now within a form you can call "Me.DoSomething()".
In summary, it is a way to add functionality to existing objects without inheritance.
An extension method is a "compiler trick" that allows you to simulate the addition of methods to another class, even if you do not have the source code for it.
For example:
using System.Collections;
public static class TypeExtensions
{
/// <summary>
/// Gets a value that indicates whether or not the collection is empty.
/// </summary>
public static bool IsEmpty(this CollectionBase item)
{
return item.Count == 0;
}
}
In theory, all collection classes now include an IsEmpty
method that returns true if the method has no items (provided that you've included the namespace that defines the class above).
If I've missed anything important, I'm sure someone will point it out. (Please!)
Naturally, there are rules about the declaration of extension methods (they must be static, the first parameter must be preceeded by the this
keyword, and so on).
Extension methods do not actually modify the classes they appear to be extending; instead, the compiler mangles the function call to properly invoke the method at run-time. However, the extension methods properly appear in intellisense dropdowns with a distinctive icon, and you can document them just like you would a normal method (as shown above).
Note: An extension method never replaces a method if a method already exists with the same signature.