Thursday, April 18, 2013

Extension Methods

I recently saw an email where a development manager was reminding his team of the value of extension methods.  This is a great method for adding base class type functionality to objects without introducing dependencies and utility classes for simple functions.

Extension methods are an easy way  to "add" functionality to existing types without having to create derived types, recompile, or otherwise modify the original type. Extension methods are a static method, but they are called as if they were methods on the target type. Using C#, there is no apparent difference between calling an extension method and the methods that are actually part of the defined type.

Here is an example extension method.  This method will extend the object string to break apart camel cased names and return a human readable name.  This can be very useful for populating drop down lists with all values of an Enumeration and other such activities.  First, we create the static method as follows.

public static string SplitCamelCase(this String input)
{
    return Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim();
}
This simply create a method (SplitCamelCase) and adds it to the methods available to any String variable in namepace scope with this class.

Then, this method can be called in the same format as any other method on the type String.


static void Main(string[] args)
{
    String testValue = "ThisIsACamelCasedSentence";
    Console.WriteLine(testValue.SplitCamelCase());
} 

These methods are quite simple to create and yet are a very powerful replacement for utility classes.  They can be used on native types as well as complex types.