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
——————————-

[code lang=”c-sharp”]
// 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;
}

[/code]

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

[code lang=”c-sharp”]

List<Customer> customerList = new CustomerList();

[/code]

//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.

[code lang=”c-sharp”]

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

[/code]

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


Discover more from Cloud Distilled ~ Nithin Mohan

Subscribe to get the latest posts sent to your email.

By Nithin Mohan TK

Technology Enthusiast | .NET Specialist | Blogger | Gadget & Hardware Geek

One thought on “Extensions Methods in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.