Enum Friendly

Have you ever seen a huge switch on an enum just to return a string? Enumerations can be tricky to deal with, mostly from the aspect of displaying them back to a user. So I whipped up a little code to make it easier to display enumerations, a little extension method. Consider this enumeration:

public enum StatusEnumeration
{
    Normal,
    NotRunning
}


If I want to display this back to a user in English, I can switch on the value, and return “Not Running” when the value is NotRunning. This can be a tad tedious, so I created an attribute to decorate an enumeration. I call it the RenderAsAttribute:



[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public sealed class RenderAsAttribute : Attribute
{
    private readonly string _renderAs;

    public RenderAsAttribute(string renderAs)
    {
        _renderAs = renderAs;
    }

    public string RenderAs
    {
        get { return _renderAs; }
    }
}


All you do is put this on the enumeration’s values, like so:



public enum StatusEnumeration
{
    Normal,
    [RenderAs("Not Running")]
    NotRunning
}


Notice I put the “RenderAs” on NotRunning. Now for the cool part, a static extension method to make this attribute useful. It would be used something like this:



string notRunningAsString = StatusEnumeration.NotRunning.Render();


Notice how I just call “Render()” on a the value of the enumeration.



public static class EnumRenderer
{
    public static string Render(this Enum value)
    {
        FieldInfo[] enumerationValues = value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
        foreach (var fieldInfo in enumerationValues)
        {
            if (value.CompareTo(fieldInfo.GetValue(null)) == 0)
            {
                var attributes = fieldInfo.GetCustomAttributes(typeof(RenderAsAttribute), false).Cast<RenderAsAttribute>();
                if (attributes.Count() == 1)
                    return attributes.Single().RenderAs;
            }
        }
        return value.ToString();
    }
}


This uses refection to look up the value on the enumeration. It’s a bit slow as far as code performance is concerned, but you can easily add caching to it by Type and value. Or, instead of using hard coded strings, you can use the string as a resource key and look up the string in a satellite assembly.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>