Quantcast
Channel: Gaurav-Arora.com » Code-Snippets
Viewing all articles
Browse latest Browse all 8

Getting description of Enum in C#?

$
0
0

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’.

The post Getting description of Enum in C#? appeared first on Gaurav-Arora.com.


Viewing all articles
Browse latest Browse all 8

Trending Articles