Thursday, July 21, 2011

Extension Methods in .Net

In this article we will see what extension methods are, why we need them and how to create them.
Extension methods are methods which allow you to extend a type, even if you don’t have the source code for that type. Let’s understand it with a simple example: Suppose you want to add IsNumeric method to string class to check whether a string is numeric or not. What you will do?
1) Either you have to create a new class inheriting from string class and then add the IsNumeric method in it. Now this solution has 2 problems. First, what if the class you want to inherit, in this case string class, is sealed. You can’t inherit from it. Second, if any how you inherit the string class then you need to make sure everyone else is using your class not the string class
2) Or create a static StringHelper class and create a static IsNumeric function in it. But this solution also has a problem that user need to know a Helper class exist.
Prior to .Net Framework 3.5 second solution was the most popular solution. But in .Net Framework concept of extension methods is introduced. Now let’s see how to create extension methods. We need to create a static class StringHelper and a static method IsNumeric as we do in the second solution.
public static class StringHelper
{
public static bool IsNumeric(this string str)
{
double val;
return double.TryParse(str, out val);
}
}
The only difference from second solution is the “this” keyword in the IsNumeric parameter. By using this keyword we are indication that it is the extension of type next to the “this” keyword. Here we have written “this string” it means IsNumeric is the extension of string type.
To use it:
string nonNumericString = "123abc";
bool Result = nonNumericString.IsNumeric();
Another benefit of using extension method is that you can easily convert helper class into extension methods without breaking the existing functionality, i.e., following code still works:
bool Result = StringHelper.IsNumeric(nonNumericString);
So now you realize it is easy to create extension methods. J