Sunday, January 22, 2012

Extension Method


An extension method is a language feature of c# from 3.0. A programmer always faces problem when he/she needs to add a new method in existing class. If it is required then what we can do are

1. Inherit the existing class in new class and implement the method
2. Implement the required functionality in other class with static modifier
3. Use aggregation

But all have its disadvantage like if we go for first option and existing class is sealed (restrict inheritance). Second option is solved problem of first one but here we have to use someone else reference (other class).
But this new feature of extension method solves these problem (some other also). This approach requires a static class with a static method.

Example

class Car 
{
}
static class ExtensionMethods
{
    public static void GetCar(this Car c)   
    {                               
        Console.WriteLine("Call extension method");
    }                               
}
The signature of extension method there is a "this" before the first argument. It shows that this is an extension method. So we can call our extension method
Car c = new Car();
c.GetCar();
Here we are calling GetCar method by car reference with.