C# Extension methods

What are they?

Every so often, I come across interesting features using C# and .NET. Introduced with C#3, Extension Methods is one of them. The name speaks for itself: They are methods used to extend functionality of existing objects without having to resort to polymorphism, wrapping or helper classes. .NET packs a fair amount of these Extension Methods with .NET 3.5 (most of them are used with LINQ.) The following example speaks for itself:

public static class Extensions
    public static double Sqrt(this double d)
        return Math.Sqrt(d);

Now, we can easily use this Extension Method where the Extensions class is visible:

double number = 100d;
double sqrt = number.Sqrt();

// Even nicer
sqrt = 100d.Sqrt()

These Extension Methods have to be defined in a static class and have to be static methods. Simply use the keyword 'this' preceding the first parameter. This parameter is also the instance of the type being extended.

Are they really useful?

I often find myself using more and more of these methods in testing environment. For instance, adding a Randomize() method to primitive types offers a great way to add non-deterministic behaviour to unit tests without the usual overhead.

private static readonly Random Random = new Random();

public static string Randomize(this string s)
    return s + Random.Next(1000);

public static int Randomize(this int i)
    return Random.Next(1, i);

public static bool Randomize(this bool b)
    return Random.Next(1) == 1;

// And so on...

It makes for very clear code while testing (maybe not so clear for booleans):

int age = 100.Randomize();
string city = "Serialville #".Randomize();
bool isAlive = true.Randomize(); // or false.Randomize(), it doesn't matter

No support for static methods

The last example, the boolean randomization, exposes a limitation of Extension Methods : They can only be applied to instances, and thus can't offer extensibility for static methods.

Some people think it wouldn't add much but, on the counterpart, I believe it could provide useful extensibility. The firsts things that come to my mind are embedded factory methods for Enums.

The following code excerpt does not compile.

public enum Star { Algol, SiriusA, SiriusB }

// Does not compile!!!
public static Star Create(static Star, string key)
    if (key == "Demon Star") return Star.Algol;
    if (key == "Sirius") return Star.SiriusA;
    else return Star.SiriusB;

// ...

// Ad-hoc factory method!
Star variableStar = Star.Create("Demon Star");

What about performance?

Extensions are just syntax-sugar offered by the C#3 compiler. As a matter of fact, extension methods are compiled into regular "helper-like" classes:

public static class Extensions
    public static void Method(this string s) {}

gets compiled to something similar to

public static class StringHelper
    public static void Method(string s) {}

So, as you might have guessed, there are no performance issues at all.

Frequent use

Common use of Extension Methods also include:

  • Added support for devlopping Fluent interfaces;
  • Extending enums (replacing the usual and unpleasant MyEnumHelper class).
Posted by: Bryan Menard
Last revised: 22 Oct, 2011 06:15 PM History


No comments yet. Be the first!

No new comments are allowed on this post.