Framework Tips VIII: Enums and Extension Methods

I have somewhat mixed feelings towards enums in C#. On the one hand, they can greatly improve readability of your code, but on the other hand, they are not much more than textual masks on numeric values. You can’t inherit from them, you can’t use enum as generic constraint (for which I see no good reason), and you can’t extend them… Or can you?

With the addition of Extension Methods in C# 3.0 you finally have the tools to put some life in them. Consider you have an enum like this:

public enum Mp3Player
{
    IPodClassic,
    IPodTouch,
    Zune,
    Zen
}

And you want to extend it to, for example, be able to tell if a player was made by Apple.

private static void Verify(Mp3Player player)
{
    if(player.IsMadeByApple())
        Console.WriteLine("It's made by Apple!");
    else
        Console.WriteLine("Someone else made it.");
}

Now, you can see that I call IsMadeByApple() on a Mp3Player instance. Here’s the piece of code that made it possible:

public static class Mp3PlayerExtensions
{
    public static bool IsMadeByApple(this Mp3Player player)
    {
        return player == Mp3Player.IPodTouch ||
               player == Mp3Player.IPodClassic;
    }
}

There’s no magic here, just a plain extension method, but with it, you can greatly improve readability of your code, by extending your enums with helper methods.