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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s