Thursday, February 4, 2010

Extension Methods

It is a special kind of static method that allows you to add new methods to existing types without deriving, recompiling or modifying the original type. The extension methods are called as if they were instance methods from the extended type.

public static class MyExtensionClass
{
public static int Multiply(this int num)
{
return num * num;
}
}

class Program
{
static void Main(string[] args)
{
int i = 3;
Console.WriteLine(i.Multiply());
Console.ReadLine();
}
}

Here are the few things we should keep in mind while using Extension Methods:

-> This keyword has to be the first parameter in the extension method parameter list. The type of the first parameter will be the type that is extended.
-> Extension methods can't access the private methods in the extended type.
-> Extension methods can be defined only in a static class.
-> If you want to add new methods to a type, you don't have the source code for it, the ideal solution is to use and implement extension methods of that type.
-> If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called. Extension methods cannot be used to override existing methods.
-> If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced i.e. extension methods.
-> The concept of extension methods cannot be applied to fields, properties or events.

0 comments: