Using Reflection to Get Enum Description and Value

In this article you will see how to handle enum values with descriptions.

Reflection uses the object of type Type that describes assemblies, modules and types.

Using reflection, it is possible to do many things, for example:

  • Dynamically create object instances.
  • Dynamically invoke methods.
  • Check if an object implements an interface.
  • Manipulate attributes set on objects.
  • Mock values for testing.
  • Retrieve debug information.

These are just a few things you can do with it. In this article I will show a simple example of how to use it to get descriptions of enums.

Let us say you want to display an enum in a dropdown. However, you want to have the code and description rather than just displaying the code. You can annotate your enum with the description attribute:

  1. public enum PurposeKind    
  2. {    
  3.     Development,    
  4.      
  5.     [Description("Functional Test")]    
  6.     Test,    
  7.      
  8.     [Description("Unit Test")]    
  9.     UnitTest,    
  10. }  
And to get the description we can use reflection. I will be getting the value and description and then I will add it to a dictionary as in the following:
  1. static void Main(string[] args)    
  2. {    
  3.     var valuesAndDescriptions = new Dictionary<PurposeKind, string>();    
  4.      
  5.     // gets the Type that contains all the info required    
  6.     // to manipulate this type    
  7.     Type enumType = typeof(PurposeKind);    
  8.      
  9.     // I will get all values and iterate through them    
  10.     var enumValues = enumType.GetEnumValues();    
  11.      
  12.     foreach (PurposeKind value in enumValues)    
  13.     {    
  14.         // with our Type object we can get the information about    
  15.         // the members of it    
  16.         MemberInfo memberInfo =    
  17.             enumType.GetMember(value.ToString()).First();    
  18.      
  19.         // we can then attempt to retrieve the    
  20.         // description attribute from the member info    
  21.         var descriptionAttribute =    
  22.             memberInfo.GetCustomAttribute<DescriptionAttribute>();    
  23.      
  24.         // if we find the attribute we can access its values    
  25.         if (descriptionAttribute != null)    
  26.         {    
  27.             valuesAndDescriptions.Add(value,    
  28.                 descriptionAttribute.Description);    
  29.         }    
  30.         else    
  31.         {    
  32.             valuesAndDescriptions.Add(value, value.ToString());    
  33.         }    
  34.     }    
  35. }  
Results:

    Development,Development
    Test,Functional Test
    UnitTest,Unit Test

See System.Type on MSDN for a reference of reflection methods.