0

possible duplicate of Finding an enum value by its Description Attribute

I get the description of the MyEnum from the user selected checkbox, I have to find the value and save it. Can someone help me how to find the value of the Enum given description

public enum MyEnum
{
   [Description("First One")]
   N1,
   [Description("Here is another")]
   N2,
   [Description("Last one")]
   N3
}

For example i will be give Here is Another i have to return N1, when I receive Last one I have to return N3.

I just have to do the opposite of How to get C# Enum description from value?

Can someone help me?

3
  • SomeType test = (SomeType )Enum.Parse(typeof(SomeType ), "Three"); Commented Apr 12, 2012 at 15:36
  • 2
    More simple than copying the code from the answer into your project and then just using it? Sounds pretty easy to me. Commented Apr 12, 2012 at 15:42
  • Is this simpler? Commented Apr 12, 2012 at 15:44

1 Answer 1

1

Like this:

// 1. define a method to retrieve the enum description
public static string ToEnumDescription(this 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();
}

//2. this is how you would retrieve the enum based on the description:
public static MyEnum GetMyEnumFromDescription(string description)
{
    var enums = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();

    // let's throw an exception if the description is invalid...
    return enums.First(c => c.ToEnumDescription() == description);
}

//3. test it:
var enumChoice = EnumHelper.GetMyEnumFromDescription("Third");
Console.WriteLine(enumChoice.ToEnumDescription());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.