Get Enum Description
Use System.ComponentModel for the DescriptionAttribute.
//using DescriptionAttribute = System.ComponentModel.DescriptionAttribute;
public enum Country
{
[Description("United Kingdom")]
UK,
[Description("United States")]
USA,
[Description("Belgium")]
BE
}
[TestMethod]
public void TestMethod1()
{
var name = GetDescription(Country.UK);
Assert.AreEqual("United Kingdom", name);
}
public static string GetDescription(Enum e)
{
string description = e.ToString(); //default will be the string value
//get the type and find the member
MemberInfo[] memberInfo = e.GetType().GetMember(description);
//try to find the DescriptionAttribute
object[] attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
//if we found the [Description], cast and pull off the description
if(attributes.Length> 0)
description = (attributes[0] as DescriptionAttribute).Description;
return description;
}