Skip to contentSkip to author details

Decorating an enum with the Description attribute for later use in C# with .NET

 .NET  C#

I had the need today to set a string value based on the value of an enum. Rather than creating the following code:

Edit: I added a generic method that works on all enums

string myString = null;  
switch(myEnum)  
{
    case myEnum.Value1: 
        myString = "value 1"; 
        break; 
    case myEnum.Value2: 
        myString = "value 2"; 
        break; 
    case myEnum.Value3: 
        myString = "value 3"; 
        break; 
}

I wanted to do something simpler. So, I decided to add the System.ComponentModel.Description attribute to my enum, like so:

using System.ComponentModel; 

public enum MyEnum  
{ 
    [Description("value 1")] 
    Value1, 
    [Description("value 2")]
    Value2, 
    [Description("value 3")]
    Value3
}

Then, to make it easy to use, I added an extension method to all enums:

public static string GetDescription(this T e) where T : IConvertible  
{
    string description = null;

    if (e is Enum)
    {
        Type type = e.GetType();
        Array values = System.Enum.GetValues(type);

        foreach (int val in values)
        {
            if (val == e.ToInt32(CultureInfo.InvariantCulture))
            {
                var memInfo = type.GetMember(type.GetEnumName(val));
                var descriptionAttributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if(descriptionAttributes.Length > 0)
                {
                    // we're only getting the first description we find
                    // others will be ignored
                    description = ((DescriptionAttribute)descriptionAttributes[0]).Description;
                }

                break;
            }
        }
    }

    return description;
}

This will allow you to easily get the description of the current enum value. Here is how you would do that:

string description = null;  
MyEnum testEnum = MyEnum.Value2;  
description = testEnum.GetDescription(); // description will be "value 2"

As you can see, it’s pretty easy to decorate your enum values with string descriptions. This allows you a central location to set the value.

I can even see a custom description attribute class that retrieves the description from a database. The use cases are there.

Another, more common use case for this method is to localize the values returned by using resource files representing the languages you want to display. You could have one for en-US, en-GB, es-ES, es-MX, etc, using the description Name as the key to the resource file.