The C# Programming Guide describes extension methods as,
Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original 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 client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
Below are a couple of examples that extend the string object. The first method reverses a string, functionality which appears to be missing from C#
public static String Reverse(this String oldString)
{
StringBuilder newString = new StringBuilder();
for (int i = oldString.Length - 1; i >= 0; i--)
{
newString.Append(oldString[i]);
}
return newString.ToString();
}
The next method uses regular expressions to replace characters in a string.
public static String Replace(this string originalString, string oldValue,
string newValue, bool ignoreCase = false)
{
Regex regEx = new Regex(oldValue,
RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (ignoreCase)
{
regEx = new Regex(oldValue, RegexOptions.Multiline);
}
return regEx.Replace(originalString, newValue);
}
The type of the first parameter, which has the this keyword before it, defines what type of object is being extended. Normal this. notation can be used to reference properties of the extended object from within the method.
To those of you familiar with SOLID principles the above description of extension methods will sound a lot like the Open-Closed principle (OCP). This principle states that objects should be extendable without recompiling the application, modifying the original object or changing the existing behaviour of the object. I agree to some degree that extensions methods do follow the OCP, though there is more to the principle than extending an object with static methods. For now I will leave it to you to investigate OCP further.

You must be logged in to post a comment.