Extension methods in C# 3.0

One of the coolest features of C# 3.0 is Extension Methods. It allows you to extend existing types with new methods. Didn't get it? Well, say you got a class called Car. Now you want that a string variable should have a method that returns a Car object. Now for C#2.0, to do such a thing you must have access to source code. However with 3.0, you can write an extension method called string.ToCar() which returns an object of type Car.

Most people would argue that sub-classing (inheritence) would have been a better approach. Not at all. This is not a case of abstraction but rather context senstivity. In context of my project, a string can be directly convertible ToCar().

Also most would argue, why not have a Helper class like CarHelper.ToCar(string param). Now in my case, I am really losing my Desgin Pattern. However, with Extension methods I can get my work done as if I had the source code available.

So let's take a look at how to create one. The rule is, the class containing the extension method must be static. The extension method should be static. The first parameter should be pass along with the this keyword.

static class ExtensionMethods
{
   static Car ToCar(this string name)
   {
      Car car = new Car();
      car.name = name;
      return car;
   }
}

Pretty neat huh? Now whatever namespace contains the ExtensionMethods class will have this extension method available on its string variables.

To check out a much better critical analysis of this feature, visit this article:
http://www.interact-sw.co.uk/iangblog/2005/09/26/extensionmethods

Visit me at:
http://captainron.blogspirit.com
www.AbhishekChatterjee.com

Ebook Download
View all
Learn
View all