C# Extension Methods

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;
   Console.WriteLine(num.Square());
}
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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: