ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

GetEnumDescription

Gets the description attribute assigned to an item in an Enum.

Source

public static class EnumHelper<T>
{
    public static string GetEnumDescription(string value)
    {
        Type type = typeof(T);
        var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
        
        if (name == null)
        {
            return string.Empty;
        }
        var field = type.GetField(name);
        var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
    }
}

Example

public enum EnumGrades
    {
        [Description("Passed")]
        Pass,
        [Description("Failed")]
        Failed,
        [Description("Promoted")]
        Promoted
    }

string description = EnumHelper<EnumGrades>.GetEnumDescription("pass");

Author: Chirdeep Tomar

Submitted on: 20 apr 2010

Language: C#

Type: System.Enum

Views: 39226