String and Enums

Written by Lawrence Botley

Mapping enumerated type values to strings

Enumerated types are a very useful way of binding an integer to a recognisable and readable string in your syntax.  I personally use enums a lot, especially when mapping states to a database value. Sometimes I want to display these mapped values in my user interfaces, but I am usually faced with an issue of chartacter restriction in that the enum string must only  contains alpha-numeric characters and cannot begin with a number. 

    public enum JunkFood
    {
        HotDog = 1,
        CheeseBurger = 2,
        Burreto = 3,
        OnionRings = 4,
    }

Map string via the ToString()

To work around this I used to create a separate class with a switch statement that returns a custom string according to the value passed into it. This was until a found a much more manageable approach

A little reflection decorations

    public enum JunkFood
    {
        [Description("Hot Dog")]
        HotDog = 1,
        [Description("Cheese Burger")]
        CheeseBurger = 2,
        [Description("Burreto")]
        Burreto = 3,
        [Description("Onion Rings")]
        OnionRings = 4,
    }

Now by using a little reflection magic we can determine if the value has been decrorated with a custom field attribute, in which case we return the defined value. Otherwise the default string value is returned

    public static string GetEnumDescription(Enum value)
    {
        var field = value.GetType().GetField(value.ToString());
        var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return (attributes.Any()) ? attributes.First().Description : value.ToString();
    }

To make things a little neater we can use an extended method for the enum itself so the value can be returned via a ToDescription() method. Its a shame that C# does support the overriding of the ToString() method, but according to C# 3.0 specifications, the extended method doesn't actually extend the class, but simply creates a pointer to a static method in the separate class which is linked at compile time.

    public static string ToDescription(this JunkFood value)
    {
        return GetEnumDescription(value);
    } 

And this is how it looks.. Neat! :)

© 2016 RK Consulting. All rights reserved.