# Thursday, April 24, 2008

C#3.0: Adding methods to enumerations

I'm currently doing some work with MapQuest and ran into the situation that I need to define styles for point of interest. From a code point of view I would like an enumeration, but the MapQuest API defines a series of strings to specify the style you wish to use. With C#3.0 I can now add a method to an enumeration using an extension method.

The sample below shows an enumeration for stars and an extension method for getting the value of that enumeration as a string:

public enum Stars : int
{
    Red = 31,
    Green = 32,
    Blue = 33,
    Yellow = 34,
    Orange = 35,
    Purple = 36,
    White = 37,
    Black = 38,
    Gray = 39,
    Gold = 40
}

public static class StarsExtension
{
    public static string Value( this Stars enumerator )
    {
        int v = (int) enumerator;
        return "MQ000" + v.ToString();
    }
}

I can now use this as follows:

string s = Stars.Gold.Value();

#    Comments [0] |