Usage of Extensions method in C# -Example

C# 3.0 has provided extension method. Let's know first what extension method is in c #. As name itself defines, extension method is a method which will extend/add the methods to existing types. Extension methods are special kind of static methods within static class.

Let us consider simple class.

    //This class contains single method Display.

public class Class1

{

public void Display()

{

MessageBox.Show("Hello Aravind");

}

}

 

Let's consider another class(extension class)

 

//This is the static class in which static extension method defined.

//Here i have used this key word to extend/Add method to class class1.

 

public static class ExtendMyMethod

{

public static void Extend(this Class1 ObjClass )

{

MessageBox.Show("Hello Aravind,You have extended previous method.");

}

}

 

//Accessing/using extension method of class1.

public class UsageOfExtensionMethod

{

Class1 objCls1=new Class1();//object of class1.

objCls1.Display();//Normal method defined in class1.

objCls1.Extend();//Extension method.(Extension).

}

An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods. The concept of extension methods cannot be applied to fields, properties or events. Overuse of extension methods is not good style of programming.

Next Recommended Reading Extension Methods in C#