An extension method is a method that extends an existing type. Extension methods
are convenience routines only and are not required for programming. In fact
extension methods are not even supported by the CLR directly. Instead extension
methods are implemented through the compiler.
In .NET a type can not be modified outside the assembly that defines it. As
a result many "helper" classes are created to extend a type (StringHelper for strings
and FormHelper for forms, for example). These helper classes are often static
classes with static methods that provide new functionality to existing types.
Since this paradigm is so useful v3.5 (technically the languages updated for v3.5)
added extension methods. An extension method is nothing more than a static
method of a class that contains the type that it is extending as the first parameter.
The following code might be something you'd see in v2 today.
public static class StringHelper
{
public static string GetErrorMessage ( string message )
{ return message.Split(':', 2)[1]; }
}
Here's how we'd use it:
string strMsg = "An error occurred: Access is denied.";
string strErr = StringHelper.GetErrorMessage(strMsg);
Not elegant but it works. In v3.5 we can add the Extension
attribute to the method and now it is an extension method. To call it we would
do the following.
string strMsg = "An error occurred: Access is denied.";
string strErr = strMsg.GetErrorMessage();
Internally the compiler simply extends the lookup for instance methods to include
searches for extension methods. When an extension method is used it replaces
the existing instance method call with a call to the static method. You can
verify this by dumping the code using Reflector.
Extension methods are most useful with LINQs where existing collection types are
extended to support LINQs style commands. Nevertheless it is useful elsewhere
as well. Care must be taken that this feature is not misused. Using
extension methods in lieu of proper class design (when you control the source) is
going to cause confusion and lead to poor type designs.