use reflection to get description attribute value from enum in csharp

To get the value of a Description attribute from an enumeration value using reflection in C#, you need to do the following steps:

  1. Get the type of the enumeration value using the GetType() method.
  2. Get the FieldInfo object for the enumeration value using the GetField() method.
  3. Get the DescriptionAttribute object for the FieldInfo object using the GetCustomAttribute() method.
  4. Get the value of the Description property from the DescriptionAttribute object.

Here's the code to get the Description attribute value from an enum using reflection:

main.cs
using System;
using System.ComponentModel;
using System.Reflection;

public static class EnumExtensions
{
    public static string GetDescription(this Enum @enum)
    {
        Type type = @enum.GetType();
        string name = Enum.GetName(type, @enum);
        FieldInfo field = type.GetField(name);
        DescriptionAttribute attribute = 
            Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
        return attribute != null ? attribute.Description : name;
    }
}
520 chars
17 lines

To use the above extension method, simply call it using an instance of the enum:

main.cs
MyEnum value = MyEnum.Value1;
string description = value.GetDescription();
75 chars
3 lines

gistlibby LogSnag