Skip to main content

C#: How to get description from Enum value (using Extension method).

To get the description from Enum value we can write our own string extension method and can use that method in same way, we are using other existing methods. We’ll take help of reflection to get description from Enum value.

Extension method:

using System;
using System.Reflection;
using System.ComponentModel;

public static class EnumExtensions
{
    public static string GetDescription(this Enum en)
    {
       var type = en.GetType();
       var mInfo = type.GetMember(en.ToString());
       if (mInfo.Length > 0)
       {
            var attrs = mInfo[0].GetCustomAttributes(
                       typeof (DescriptionAttribute), false);

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

       return en.ToString();
    }
}

 Usage: Test the extension method as:

//Declare Gender Enum.
public enum Gender
{
    [System.ComponentModel.Description("Male")]
    Male = 1,
    [System.ComponentModel.Description("Female")]
    Female = 2,
}

//Get description from enum value as:
Gender.Male.GetDescription();
Gender.Female.GetDescription();

Comments