Enum description using reflection and extension methods

I don’t take credit for this as it was written by another developer on the the project, but I thought it was good and worth writing about.

On the current project I’m working on we use a lot of enumerations for statuses which are shown in drop-down lists and grids. It can get a bit ugly from a UI perspective when simply using the ToString method as enumeration values cannot have spaces and are usually shortened for ease of use when coding.

One way to overcome this is to add a description attribute to each enumeration value and write an extension method that uses reflection to obtain the value in the description attribute.

The description attribute is part of the System.ComponentModel namespace so we need to import this.  The attribute value can then be set on each enumeration value:

public enum Status : int
{
    [Description("Application pending")]
    Pending = 0,
    [Description("Application received")]
    Received = 1,
    [Description("Application processing in progress")]
    Processing = 2,
    [Description("Application processed")]
    Processed = 3
}

The next step is to create the extension method.  Extension methods were introduced in  C# 3 and allow you to easily add new methods to existing types.  Scott Guthrie has a good blog post on them here.  Extensions methods need to be static, and contained in a static class.  In the method signature the ‘this’ keyword is used to indicate which type the extension method is for.  Below is the extension method that will get the description attribute for an enumeration using reflection.

public static string Description(this Enum enumeration)
{
    string value = enumeration.ToString();
    Type type = enumeration.GetType();
    //Use reflection to try and get the description attribute for the enumeration
    DescriptionAttribute[] descAttribute = (DescriptionAttribute[])type.GetField(value).GetCustomAttributes(typeof(DescriptionAttribute), false);
    return descAttribute.Length > 0 ? descAttribute[0].Description : value;
}

Any enumeration will now have a method called Description that will try to return the value of the description attribute, and if the attribute is not present return the result of calling ToString.  For example:

Console.WriteLine(Status.Processing.Description());

 
Will display:

exmethod1

As the extension method is for Enum, and not just the Status enumeration I created, we could do this:

Array values = Enum.GetValues(typeof(Status));
foreach (Enum e in values)
    Console.WriteLine("{0} - {1}", e, e.Description());

The result here would be:

exmethod2

There are lots of uses for extension methods which are used extensively with Linq, but I particularly like this idea to provide a more readable value for an enumeration.

Posted on by Joe in C#

Add a Comment