Monday, January 14, 2008

C# 3.0 Extension Methods

The new extension feature in C# 3 allows us to add New definitions to existing classes. In other words, we can introduce new methods to any class without inheriting our own type from it.

For an example, take the String class. This calss already has some methods for string manipulation like Split(), Trim(), .... Suppose we would like to add a new feature to the String class, like GetWordCount() so we could use it like this:

string str = "The new feature";
int words = str.GetWordCount();

Note that we have not created a new type. We are using the same old String class but with a new member method. We can achieve this by extension method.
static int GetWordCount(this string s)
//Word count logic goes here
return count;
This method can be inside any class. The only thing matters is in what namespace the method is. If the GetWordCount method is in a namespace called MyExtensions, you can load the extension by adding the using directive like:

using MyExtensions;

So the String class will appear to have an extra method called GetWordCount whenever you use this namespace.

Refer to MSDN for better in-depth article.

No comments: