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 an IsNumeric method to a string class to check whether a string is numeric or not. What will you do?
- Either you have to create a new class inheriting from the string class and then add the IsNumeric method to 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.
- Or create a static StringHelper class and create a static IsNumeric function in it. But this solution also has a problem that the user needs to know a Helper class exists.
Prior to .Net Framework 3.5 the second solution was the most popular solution. But in the .Net Framework 3.5 the concept of extension methods was 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 the second solution is the "this" keyword in the IsNumeric parameter. By using this keyword we are indicating that it is the extension of the type that is next to the "this" keyword. Here we have written "this string", which means IsNumeric is an extension of the string type.
To use it:
string nonNumericString = "123abc";
bool Result = nonNumericString.IsNumeric();
Another benefit of using an extension method is that you can easily convert a helper class to an extension method without breaking the existing functionality, i.e., the following code still works:
bool Result = StringHelper.IsNumeric(nonNumericString);
So now you can see it is easy to create extension methods.