Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
- Define a static class to contain the extension method.
The class must be visible to client code. For more information about accessibility rules, see Access Modifiers (C# Programming Guide).
- Implement the extension method as a static method with at least the same visibility as the containing class.
- The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.
- In the calling code, add a using directive to specify the namespace that contains the extension method class.
- Call the methods as if they were instance methods on the type. Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.
So how do you write an extension method?
Well thats easy, you simply put the “this” keyword as the first parameter of the extension method ~ which is a static method in a class. So you could write code as below
public static class myExtensions
public static void SpankMonkey(this int i)
Sure you could have complicated implementations such as –
public static int DoubleMe(this int i)
return i + i ;
You could call the above using –
int i = 10;
Console.WriteLine(i.DoubleMe()) ; // Prints 20
You could also pass in a “generic” instead of an “int” or “string” etc.
Extension Method Resolution:
An obvious question here is, what if your class implements a method, AND there is an extension method that looks, talks, walks the same way – that is of the same name? Which gets called?
The answer is – “Whichever is the closest”.