How to

use and retrieve enum description attribute

Published: 4. November 2011 | Updated: 4. November 2011
License: Microsoft Public License (MS-PL)
Categories: Framework » Attributes, Framework » Enums
Tags: Attributes C# Enums Text
Was this snippet helpful for you? YESYES / NONO

Import namespaces

using System.ComponentModel;
using System.Reflection;

Code

public static string GetEnumDescription(Enum enumValue)
{
    string enumValueAsString = enumValue.ToString();

    var type = enumValue.GetType();
    FieldInfo fieldInfo = type.GetField(enumValueAsString);
    object[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attributes.Length > 0)
    {
        var attribute = (DescriptionAttribute)attributes[0];
        return attribute.Description;
    }

    return enumValueAsString;
}

Use

public enum MyEnum
{
    [Description("The First")]
    First,
    [Description("The Second")]
    Second,
    [Description("The Third")]
    Third,
}

// retrieve
string description = GetEnumDescription(MyEnum.Third);
Console.WriteLine(description);
Console Output:
The Third
Send us feedback about this snippet »



Related Snippets: