Extension Methods - Yet another cool feature brought into .Net realm with C# 3 and VB.Net 9. Extension methods allow you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. In a way it allows you to extend an existing type with new functionality, without having to sub-class or recompile the old type.
The Need:
While programming, many time situations arise where it is necessary to add functionality to an existing class—for instance by adding a new method. Normally we can do this by modifying the existing class's source code, but this forces to recompile all binaries with these new changes and more important, requires that the programmer have access to the source code, which is not always possible, for example when using classes from a third-party assembly or out-of-box .Net base class libraries. This can be typically worked around in one of following ways:
- Inherit the class and then implement the functionality in an instance method in the derived class. [What if that class is sealed or final, restricting inheritance]
- Implement the functionality in a static method added to a helper class. [Less intuitive - as it requires a reference to a separate class instead of using the methods of the class in question directly.]
- Use aggregation instead of inheritance.
Extension Methods - An Handy rescue
Extension Methods allows you to extend an existing type with new functionality, without having to sub-class or recompile the old type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
For instance, you might like to know whether a certain string was a number or not (IsNumeric functionality). The usual approach would be to define a static function and then call it each time passing corresponding string as input.
MyUtils.IsNumeric(inputString)
But now with concept of extension methods - you can actually extend the String class to support this directly. And your call would look like this:
inputString.IsNumeric()
You do it by defining a static class, with a static method in it.
public static class MyExtensionMethods
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
Note the first parameter preceded by the 'this' modifier, it specifies which type the method operates on or rather which type or class it is extending. The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for that particular type. And that's actually all you need to create an extension method.
Now you can call the IsNumeric() method directly on strings, like this: someString.IsNumeric()
The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable(Of T) types.
To defining and call the extension method
-
Define a static class to contain the extension method.
-
The class must be visible to client code. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. For more information about accessibility rules, see Access Modifiers (C# Programming Guide).
-
Implement the extension method as a static method with at least the same visibility as the containing class.
-
The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.
-
In the calling code, add a using directive to specify the namespace that contains the extension method class.
-
Call the methods as if they were instance methods on the type.
Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.
Naming Conflicts in Extension methods and Instance methods: In C# 3.0, both an instance method and an extension method with the same signature can exist for a class. In such a scenario, the instance method takes precedence over the extension method. Note that neither the compiler nor the Microsoft Visual Studio IDE warns about the naming conflict.
A good extension method should:
- Apply to any possible instance of the type it extends.
- Simplify logic and improve readability/maintainability.
- Apply to the most specific type or interface applicable.
- Be isolated in a namespace so that it does not pollute IntelliSense.
More Related links
- Extension Methods Explained on Wikipedia
- MSDN: How to: Implement and Call a Custom Extension Method (C# Programming Guide)
- MSDN: C# Programming Guide - Extension Methods
Final words : Extension Methods are a lot like sugar, they taste so nice and sweet, but they'll rot your teeth if you eat them too much.
0 comments
Posts a comment