add

Thursday, May 28, 2009

Using Extension Method

Why Extension Method ?

Many time we need a requirement where we need to add a new method to a class. Addition of new method is very easy if we have the class code but what if we don't have the source code of that class? We just have the dll..

One option is to inherit the existing class and add the new method or modify any existing method. The problem with this option is that it may not be possible every time due to OO Principles.

Here comes the concept of Extension Method

How to Use Extension Method

Here is a step by step tutorial on how to use extension method.

Suppose the case is that, we need to have a method called 'Next' and 'Previous' that will give us the next and previous number of the given number.

We will do it by using Extension method.

Step 1: Create a new Console application:
Step 2: Add a new class Item and name it 'Ext.cs'.
Step 3: Renamen the namespace of that class to System.
Step 4: Add the followign code:

public static class Ext
{
public static int Next(this int A)
{
return A + 1;
}
public static int Previous(this int A)
{
return A - 1;
}

}


The class will look like this:



Few things to explain:

1. Namespace has been renamed to 'System' since almost all C# source files have a using System; declaration, this extension method is effectively going to be available globally

2. An extension method must be static and public, must be declared inside a static class, and must have the keyword this before the first parameter type, which is the type that the method extends. Extension methods are public because they can be (and normally are) called from outside the class where they are declared.

Step 5: How to use an Extension Method:

We have created a public , static method using namespace System. Now the question is how to use it.
In step 1 , we have created a console application, so in the Main method of Program.cs, write this:

int a=10;
Console.WriteLine("Number after {0} is {1}", a, a.Next());
Console.WriteLine("Number after {0} is {1}", a, a.Previous());
Console.ReadLine();

You will notice here, as soon you type 'a' and press ., static mehtods declared in the Ext.cs will appears in intellisence and with a new symbol that marks it as extension.



Step 6: Build the application and press F5:

The output window will show the desired result:



Summary

Although this is not a big revolution, one advantage could be Microsoft IntelliSense support, which could show all extension methods accessible to a given identifier. However, the result type of the extension method might be the extended type itself. In this case, we can extend a type with many methods, all working on the same data. LINQ very frequently uses extension methods in this way.

The most common use of extension methods is to define them in static classes in specific namespaces, importing them into the calling code by specifying one or more using directives in the module.

No comments: