Extention Method in C#

This is a new feature that has been added in c# 3.0 that allows  to add new methods under in existing class without editing source code of the class.
 

The concept of the extension method is near similar to concept of inheritance , where in inheritance we can add new functionality to an existing class without editing the source code with the help of a child class. but here the old and new methods can be accessed by using object of the new class i.e child class.
 

In case of extension methods also we can add new methods to an existing class without editing it's source code by taking a new class. Where the new class is not a child class after defining the method under new class and we can access the old and new methods here with the object of the old class only.

 

Defining extension methods : an existing method can be defined only under “Static Method”.

 

Because extension methods are define under static classes they need to defined as static method but while invoking the method s we access them also instance method only .

 

The first parameter of an extension method is referred as binding parameter  used for specifying to which class the method belong s and this parameter is not concerned while invoking the method.

 

If an extension method defined with a parameter while invoking we have only (n-1) parameters.

 

One extension method can only bound only with one class because on extension method allows only one binding parameter but a single static class any number  of extension methods can be defined binding with different classes.

 

Add a class Original.cs and with the following code :

 

 

Class Original

{

Public int a = 50;

Public void show1()

{

    Console.WriteLine(“method1 : “ + this.a”);

}

        Public void show2()

        {

   Console.WriteLine(“method2 ”);

 }

}

 

Add other class OtherClass.cs, write following by making a class as Static.

 

Static  Class OtherClass

{

Public static void show3(this Original obj)

{

    Console.WriteLine(“method3”);

}

 

Public static void show4(this Original obj, int x)

{

       Console.WriteLine(“method4  :” + x);

     }

 

         Public static void show5(this Original obj)

{

       Console.WriteLine(“method5 : ” + obj.a);

       }

 

}

 

Add another class TestOriginal.cs and write the following code

 

Class TestOriginal

{

    Static void main()

    {

         Original obj = new Original();

         Obj.Show1();    Obj.Show2();

         Obj.Show3();    Obj.Show4(10); Obj.Show5();

    }

}