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?

Community
  • 1
  • 1
helpme
  • 570
  • 1
  • 7
  • 26

1 Answers1

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());
code4life
  • 15,655
  • 7
  • 50
  • 82