Friday, 22 November 2013

Using Text Description in Enumeration Type

If we would like to have text description for an enum, we could use Description attribute like below:
public enum MyEnum
{
 [Description("Value One")]
 One,

 [Description("Second Value")]
 Two
};

Then to get the description text we could use something like the codes below. Usually we would put this in a helper class.
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();
}

Finally the usage:
Helper.GetEnumDescription(MyEnum.Two);


Reference:
http://blog.spontaneouspublicity.com/associating-strings-with-enums-in-c

No comments: