Give Your Enums a Friendly Name Image

Give Your Enums a Friendly Name

December 21, 2014      .net Programming

Using an Enum in code makes sense for a variety of reasons. Often, an enum-based property is also something that a user can select through a UI of some sort. Code maintainability dictates that the UI should represent the enum by binding the UI element directly to the enum itself. But that leaves the user picking from a list of values that don't necessarily make sense. Here is my solution.

Consider the following Enum:

public enum EducationLevel

   SomeHS,
   HighSchool,
   GED,
   College2,
   College4,
   Masters,
   PHD
}

As you can see, we are defining how much education a person has. Obviously the system at hand needs this information and this would be entered in the UI on a per-person basis. So rather than training users on what each of these mean, we would decorate items with the System.ComponentModel.DescriptionAttribute attribute as follows:

public enum EducationLevel
{
   [Description("Some High School")]
   SomeHS, 
   [Description("High School Degree")]
   HighSchool,
   GED,
   [Description("2-Year College")]
   College2,
   [Description("Bachelor's Degree")]
   College4,
   [Description("Master's Degree")]
   Masters,
   [Description("PhD")]
   PHD
} 

Referencing my previous article we know how to get the enum values in the order they are entered into the code. So how we pull the description instead?

Type enumType = typeof(EducationLevel);
System.Reflection.FieldInfo[] fields = enumType.GetFields();
foreach (System.Reflection.FieldInfo f in fields)
{
   if (f.Name.Equals("value__"))
      continue;
   string text = f.Name;
   object[] cAttrs = f.GetCustomAttributes(typeof(DescriptionAttribute), false);
   if ((cAttrs != null) && (cAttrs.Length > 0))
      text = ((DescriptionAttribute)cAttrs[0]).Description;
   Console.WriteLine(text);
} 
Share It