Hi
Extension Methods are really cool new features in the C# 3.0. With extension methods we can attach new function to the existing (even the value types). It does not matter if do not have access to the type, we can still add new methods to the type.
For example I can write an extension method to trace, response or print every element of the collection. This is very simple to be done. Here is the example of the trace method.
public static class Ext
{
public static void Trace<T>(this ICollection<T> col)
{
foreach(T t in col)
Trace.Write(t);
}
}
Here I have added a method Trace to the ICollection(All the collection inherit from this type) type so now I can get all the values of a collection in the trace by writing the code like this.
List<string> col = new List<string>();
col.AddRange (new string[] {"col1", "col2", "col3", "col4"});
col.Trace();
There are some restrictions in creating the extension methods. Which are listed below.
-
The extension method has to be inside a static class
-
The extension method has to be a static method.
-
The first parameter to the method has to be qualified using "this"
-
The "this" keyword will be followed by the type where the extension method will be added.
Also we can also call the method like Ext.Trace(col);
The benefit that we get is that the code looks more elegant.
Thanks
Vikram