Editorials

Extension Methods

One of my favorite features of some object oriented languages is the ability to write methods extending the capabilities of an existing class, while not modifying the original code in any fashion. Java, C#, F# and JavaScript are well known for this capability.

In C#, it works by creating a method where the input has a single parameter of the same type as the class you wish to extend. The parameter is prefixed with the keyword “this”, referring to an instance of the object to be extended when the method is called. Your method then becomes a fluent extension of the existing class. In C# you start with a non-nested static class to create your static method. In that class you define a static method…further descriptions follow.

Let’s say you want to create a string extension to make every other character Upper or Lower Case. So, the word “wonderful” would be transformed into “WoNdErFuL”. Let’s create a method called ToBumpy as an extension of the string class. Here is a method implementing our requirements for ToBumpy().

Public static class StringExtensions

{

public static string ToBumpy(this string theString)

{

if (string.IsNullOrEmpty(theString))

{

return string.Empty;

}


var myString = theString.ToLower();

char[] theChars = myString.ToCharArray();


for (int i = 0; i < myString.Length; i+=2 )

{

theChars[i] = char.ToUpper(theChars[i]);

}


return new string(theChars);

}

}

Now all you have to do to use the ToBumpy() method is have an instance of a string. The string can then call ToBumpy, just like other methods you already use such as ToUpper() or ToLower().

Here’s an example:

Console.Write(“WonderFul”.ToBumpy());

WoNdErFuL

var myString = “WONERFUL”;

Console.Write(myString.ToBumpy());

WoNdErFuL

I found a great site with hundreds of extension methods contributed by many different people. Check it out at http://www.extensionmethod.net.

Do you use extension methods? While they are the only way to modify existing classes for which you don’t have source, you do lose the encapsulation of the method with the class. Do you find this a problem in real world use? Do you prefer this as an implementation of the Open/Closed principle of SOLID? Do you even know what I’m talking about? Share your thoughts with us in a comment or drop an Email to btaylor@sswug.org.

Cheers,

Ben