Monday, November 28, 2011

Extension Methods in c#

It is an approach which can be used for extending the functionalities of a class even if the source code of the class is not available.Extension methods can be used for adding new methods to a class using static class.After defining an extension method these methods can be accessed using in object of the actual class to which they were added.To define an extension method we need to fallow the below rules and regulations

1.An extension method should always per-defined under a static class
2.As a methods are defined under the static class they need to be defined as static methods.but when they are found to actual class they can converted to instance methods.Every extension methods should have one mandatory parameters.e The class to which the method should be bound.A single static class can add extension methods to any no of classes

Example:
class extension
{
  public int a=10;
  public void display1()
   {
    console.writeline("method1");
   }
  public void display2()
   { 
    console.writeline('method2");
   }
  static void main()
   {
    extension e=new extension();
    e.display1();
    e.display2();
    console.readline();
   }
}
Add one more class to project naming it as Staticclass.cs.In this
public static void display3(this extension e)
{
 console.writeline("method3");
}
public static void display(this extension e,int x)
{
console.writeline("method4+"x");
}
public static void display(this extension e)
{
console.writeline("methods5"+e.a);
}
After defining three extension methods now the class extension contains five methods in it .you can test it by adding a new class the project and naming it as text extension.cs and with fallowing
static void main()
{
extension e=new extension();
e.display1();
e.display2();
e.display3();
e.displa4(10);
e.display5();
}

No comments:

Bel