Simple but Useful Extension Methods

In my previous post, I gave a fairly quick introduction to extension methods in C#. This post will present two examples to illustrate how readability can be improved by means of very simple extension methods.

One of the most common checks you perform on a string is whether it has any value. The string type has a static IsNullOrEmpty method intended for this purpose. The reason this method is static is that it could never check for null if it was an instance method. Rather, it would throw a NullReferenceException. Consider this extension method, however.

public static class Extensions
{
	public static bool IsNullOrEmpty(this string value)
	{
		return string.IsNullOrEmpty(value);
	}
}

Being static, this method can be invoked even when value is null. But, due to the fact that it is defined as an extension method, you can invoke it using instance method syntax, improving readability.

string foo = null;
if(foo.IsNullOrEmpty())
{
	// Do something
}

Another common scenario is parsing string values into corresponding enumeration values. Again, .NET provides a static method for this purpose. The Enum type has a static Parse method which takes a Type parameter and a string parameter, and returns an object which then has to be casted to the specified type.

string day = "Monday";
DayOfWeek dayOfWeek = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day);

The signal-to-noise ratio of that second line of code is rather poor. Consider the following generic extension method.

public static class Extensions
{
	public static T ToEnum<T>(this string value)
	{
		return (T)Enum.Parse(typeof(T), value);
	}
}

Notice how this method does exactly the same as the concrete DayOfWeek example above. With this extension method in place, however, each parse operation can now be reduced to the following.

string day = "Monday";
DayOfWeek dayOfWeek = day.ToEnum<DayOfWeek>();

Again, the major benefit is with the readability.

The examples in this post are extremely simple, but they illustrate how easily you can improve readability by simply wrapping existing functionality in a reasonably named extension methods. For more handy extension methods, I recommend browsing through this StackOverflow thread:
http://stackoverflow.com/questions/271398/post-your-extension-goodies-for-c-net

Extension Methods in C#

Extension methods were introduced as a C# feature in version 3. An extension method is really nothing but a plain old static method. The difference is how you can invoke that static method. Conventionally, a static method is called by explicitly telling the compiler which class contains the method.

int absoluteValue = Math.Abs(-5);

Here, the static method Abs is called on the Math class with the argument -5. If the Abs method was declared an extension method, the first parameter could have been passed using instance method invocation syntax.

int absoluteValue = -5.Abs(); // Not valid

The most obvious place to find extension methods in .NET is in the LINQ namespaces. One such extension method is Enumerable.Where. Consider these two invocations of this method.

var values = new int[]{ 1, 2, 3, 4, 5 };

var filtered1 = values.Where(i => i < 3);
var filtered2 = Enumerable.Where(values, i => i < 3);

The two calls to Where are equivalent. In fact, the C# compiler will simply transform the former syntax into the latter before compilation. This transformation does require, however, that the compiler looks for a static method called Where in all static classes in all included namespaces, but this operation is reasonably fast.

Creating your own extension methods is very easy. The only requirements are that the method is static, its class is static and the first parameter of the method specifies a this keyword. Consider this example

public static class IntExtensions
{
	public static bool IsEven(this int value)
	{
		return value % 2 == 0;
	}

	public static bool IsOdd(this int value)
	{
		return !value.IsEven();
	}
}

These two extension methods will seemingly augment all ints with the two methods IsEven and IsOdd, making the following code compile.

if(2.IsEven() && 3.IsOdd())
{
	Console.WriteLine("All is good");
}

Extension methods can drastically improve readability, especially when performing multiple operations. Consider these two lines of code.

Utils.DoSomethingElse(Utils.DoSomething(Utils.Transform(x, "arg1"), "arg2"));
x.Transform("arg1").DoSomething("arg2").DoSomethingElse();

There is no argument that the second line is much easier to interpret while reading than the first line. Extension methods make such a “chaining” syntax of static method calls possible.

Before you go bananas and convert all your static utility methods to extension methods, however, consider this warning from MSDN:

Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible.

In my next post, I will present a couple of simple but handy extension methods which can be useful in most any project.