Monday, July 30, 2007

Extension Methods

I was looking at the new features (putting aside WPF, WCF , Workflow etc) brought in the new version of C#, ie, 3.0. One of first features that caught my eye was Extension methods.

What does it do ??
Extension Methods allows to extend any class with additional (Instance level) methods without having code level access to the particular class


The Need ???
Suppose you need to provide an additional function to classes created by someone else ( you don’t have its code ) or say you want to add a new function Reformat to String Class, you could use the Extension Methods approach.

Example ?

using MyExtension;

class Program
{
static void Main(string[] args)
{
string myString = "Hello";
Console.WriteLine(myString.TestMe());
Console.ReadLine();

}
}


namespace MyExtension
{
public static class ExtString
{
public static string TestMe(this string m)
{
return "Calpine";
}
}
}

Points To Note
=> Prefixing "this" in the first parameter of the function TestMe. This lets the compiler know it’s a extension method for type specified for this very parameter

=> Extension methods are written as static function of a static class

Important
Extension Methods have lowest precedence. This means if a function with same name is already defined for that type, then that one would take precedence over the extension method.

So what do you think about this feature ??