How to get C# Enum description from value?

Posted by davekaro on Stack Overflow See other posts from Stack Overflow or by davekaro
Published on 2010-04-16T01:44:00Z Indexed on 2010/04/16 1:53 UTC
Read the original article Hit count: 1098

Filed under:
|

I have an enum with Description attributes like this:

public enum MyEnum
{
    Name1 = 1,
    [Description("Here is another")]
    HereIsAnother = 2,
    [Description("Last one")]
    LastOne = 3
}

I found this bit of code for retrieving the description based on an Enum

public static string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

This allows me to write code like:

var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))
                         select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) };

What I want to do is if I know the enum value (e.g. 1) - how can I retrieve the description? In other words, how can I convert an integer into an "Enum value" to pass to my GetDescription method?

© Stack Overflow or respective owner

Related posts about c#

Related posts about enums