October 30, 2008 Leave a comment
Extension Methods is new to C# 3.0 and allows you to attach new methods to .Net data types. I have created a simple example. I have added an extension method to the .Net Int32 type to calculate the square value of an integer.
public static class Program
static void Main(string args)
Int32 num = 2;
public static Int32 Square(this Int32 n)
return n * n;
I have added the Square function to the Int32 type by adding the this keyword before the first parameter in the function which informs the compiler that this method is an extension method of the parameter type.
Note: Both the extension method and its class must be static
In case you have an extension method and an instance method with the same name and signature, the instance method will take precedence over the extension method.
Note: Events, Properties, and operators can not be extended.