Friday, December 2, 2011

Evolution of Extension Methods


When I first heard about extension method in C#, I was excited that’s what I have been in OOPS. But to tell you the history about extension methods they got evolved out of Operator overloading, if you closely monitor syntax for Operator overloading which used to be in C++ as :
Public static Type1 operator op(Type1 t1,Type1 t2)
{
…….
}
 
Here Type1 could be any class, and “op” is any operator which is +,++, -, ..ext
 
An example of “+” operator overloading for “Complex” class would be
 
Example:
public static Complex operator +(Complex c1, Complex c2) 
{
   return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
 
 
Now if you closely monitor syntax for extension methods it is…
 
Extension Methods:
Public static Type2 MethodName(this Type1 objType1,…. [other type variables])
{
….
}

Here Type2 could be any type that would be returned by Extension method, and as it says first variable has to be of the type for which you are defining extension method…
So if you monitor it closely you can see that I am attaching an extra method to a type by defining its functionality for Methodname (which is like an operator for me).

No comments:

Post a Comment