Quick Tip: Enum to Description in C#

A common hindrance in creating enums is the desire to display text other than its’ name or integer value.

Take for instance this enum:

public enum Colors
{
  Red,
  Green,
  Blue
}

Simple right? If the end user needs to see the names of the values, we can just display them as is; life is good.

Now the requirement comes in and says that we need to add a new color “Light Blue”.

public enum Colors
{
  Red,
  Green,
  Blue,
  LightBlue,
}

Oh no what to do? Maybe we can write a parser to insert spaces whenever there is a capital letter; what do we do if there are multiple capital letters in a row? And you just over herd the business discussing whether we should display “Electric Green” instead of “Green” for the Green value…

In any case, sooner or later you’ll run into a situation where you’ll need to get a description for your enums instead of their names. I’d like to present a fairly simple yet useful approach to giving these enums descriptions. *

First, we need to reference and import System.ComponentModel.

using System.ComponentModel;

Next, we decorate our enums with description attributes, setting their desired description where it varies from the enum name.

public enum Colors
{
  Red,
  [Description("Electric Green")]
  Green,
  Blue,
  [Description("Light Blue")]
  LightBlue,
}

Next, we implement some code to get the description attribute if one exists if not return the enum name.

public static class EnumExtensions
{
  public static string GetDescription(this T enumerationValue)
    where T : struct
  {
    var type = enumerationValue.GetType();
    if(!type.IsEnum)
    {
      throw new ArgumentException($"{nameof(enumerationValue)} must be of Enum type", nameof(enumerationValue));
    }
    var memberInfo = type.GetMember(enumerationValue.ToString());
    if(memberInfo.Length > 0)
    {
      var attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

      if(attrs.Length > 0)
      {
        return ((DescriptionAttribute)attrs[0]).Description;
      }
    }
    return enumerationValue.ToString();
  }
}

Finally, we consume our new method and display the descriptions.

Console.WriteLine(Colors.Green.GetDescription());
// Electric Green

I like this approach when simplicity is our goal. It’s nice to not have to hunt around the code for the function that converts them to the descriptions.

*: Where exactly you store your strings and whether they be localized or not is a topic for another post.