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"));

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.


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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s