Extension Methods

This is one feature in C# 3.0 that I’ve been really looking forward to for a long time.

It gives us the ability to extend classes that we didn’t author and can’t inherit. One of the key benefits I see in this is the ability to extend primitive .NET classes such as String, Int32 etc. These classes can’t be inherited so there hasn’t previously been a neat way of extending them.

The following example adds a rather simplistic method to the System.Int32 type – IsPrime which simply returns true or false depending upon whether the integer is a prime number. [Ok – I know the method is half done and performs poorly – its meant to explain extension methods not prime number evaluation algorithms].

    public static class ExtensionTest
    {
public static bool IsPrime(this int value)
{
for (int denominator = 2; denominator <= value / 2; denominator++)
{
if (value % denominator == 0)
return false;
}
return true;
}
}
    public class Test
    {
public void TestMethod()
{
for (int i = 0; i < 100; i++)
{
if (i.IsPrime())
System.Diagnostics.Debug.Write(i + ", ");
}
}
}

What I really love about the .NET implementation is the way in which extension methods are understood by the IDE intellisense and how you bring the extension methods into scope by importing (using) the namespace. This means the you only see the relevant methods based on the current namespace scope.

The intellisense displays a little arrow against the standard method icon to indicate that the method in question has been extended by a static extension method. Very cool.

 Intellisense drop down showing IsPrime extension method