Extensions Methods in C#

Extensions Methods in C#
——————————-
Extension method is new to C# 3.0 (.NET 3.5).Its allow you to add new method to the existing class.

a. Extension method allows you to add new method to the existing class without modifying the code, recompiling or modifying the original code.
b. Extension method are special kind of static method but they are called using instance method syntax. Their first parameter specify which type the method operate on, and the parameter is precede by “this” modifier.
c. Extension method are only in scope when you explicitly import the namespace into your source code with “using” directive.
d. It allows us to implement custom, reusable methods on our existing .NET Class Library classed

Extension Methods Creation/Implementation
——————————-

// Here is the implementation sample, which converts a List<T> to DataTable object. 
// this keyword just next to List<T> specifies the source object on which this extension method will operate. 
public static DataTable toDataTable<T>(this List<T> source)  
{
   DataTable result = new DataTable();


   //TO-DO: Some implementation to create data table


   return result;
}

How to Use
——————————————

Suppose we have a list of Customer Objects, which we want to convert as a DataTable, table having Customer class properties as Columns.

lets declare like


List<Customer> customerList = new CustomerList(); 

//Dot net does not support some direct methods for certain requirements we have. So they are providing extensiblity.

you will call Convert extension method like below.


DataTable dtCustomers = customerList.toDataTable<Customer>(); 
// Here it calls toDataTable() extension method. since we mentioned "this" for a List<T>

You can see the method toDataTable() appearing among the remaining existing methods in Visual Studio intellisense.

Notes:
———————
1. Each Extension methods should start with a source parameter, the source object on which this extension method will operate.
2. Source object should be marked with “this”
3. Method should be STATIC

Advantages
—————————
1. We can write our own logic based on our business needs, which operate on source data.
2. Code Reusablity.
3. Code Extensiblity.
4. A Nice practice / way of programming