Saturday, June 11, 2011

Extention Methods in C#?


Extention Methods are special type of Static methods which can be add to existing types without recompiling or modifing the original type.
Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Syntex:
Declare the class and its method as Static and the first parameter of function is preceeded by this key word.
Page 1.
namespace ExtensionMethods
{
public static class Utility
{
public static void Print(this object o)
{
Console.WriteLine("Called print: {0}", o.ToString());
}
public static int Increment(this int i)
{
return i++;
}
public static int Decrement(this int i)
{
return i--;
}
public static int Double(this int i)
{
return i * 2;
}
public static int Bonus(this int i)
{
return i + 5;
}
}
}
Page 2. Client Code
If we want to call the extention methods in our code than we need to first add the namespace of extention method.

namespace UseExtensionMethods
{
using ExtensionMethods;
static class Program
{
static void Main(string[] args)
{
int anotherNumber = 10;
int i = 7;
//e.g 1. Print(i);
i.Print();
//e.g 2.
//In the below line Increment method is directly called on variable anotherNumber.

anotherNumber.Increment();
//e.g 3.
//IN the below step first Method Increment is called and the method o/p is supplied to bonus method than decrement method is called and o/p is
//given to print method and finally result will be print on the screen.

anotherNumber.Increment().Bonus().Double().Decrement().Print();
Console.ReadLine();
}
}
}

No comments: