Getting description of Enum in C#?

In this code snippet we will look an easy way to get description of Enum.

Lets discuss a simplest way, just need to define an extension method:

Our pre-defined Enum:

public enum AuthorLevels  
{  
  [Description("No level")]  
  None,  
  Description("Starter")]  
  Bronze,  
  [Description("Intermediate")]  
  Golden,  
  [Description("Advance")]  
  Platinum  
}

Define an extension method:

public static class EnumExtensionMethods  
    {  
        public static string GetEnumDescription(this Enum enumValue)  
        {  
            var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());  
  
            var descriptionAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);  
  
            return descriptionAttributes.Length > 0 ? descriptionAttributes[0].Description : enumValue.ToString();  
        }  
    }

Do not forget to add following namespace, in above:

using System.ComponentModel;

Now, call this extension method as:

var authorLevel = AuthorLevels.Platinum.GetEnumDescription();

Above will give you: ‘Advance’.

Leave A Reply