Skip to content

Instantly share code, notes, and snippets.

@curzona
Created April 6, 2014 09:44
Show Gist options
  • Select an option

  • Save curzona/10003743 to your computer and use it in GitHub Desktop.

Select an option

Save curzona/10003743 to your computer and use it in GitHub Desktop.
Adding Descriptions to your Enumerations
// From http://www.codeproject.com/Articles/13821/Adding-Descriptions-to-your-Enumerations
public class EnumUtils<T>
{
public static string GetDescription(T enumValue, string defDesc)
{
FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
if (null != fi)
{
object[] attrs = fi.GetCustomAttributes
(typeof(DescriptionAttribute), true);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return defDesc;
}
public static string GetDescription(T enumValue)
{
return GetDescription(enumValue, string.Empty);
}
public static T FromDescription(string description)
{
Type t = typeof(T);
foreach (FieldInfo fi in t.GetFields())
{
object[] attrs = fi.GetCustomAttributes
(typeof(DescriptionAttribute), true);
if (attrs != null && attrs.Length > 0)
{
foreach (DescriptionAttribute attr in attrs)
{
if (attr.Description.Equals(description))
return (T)fi.GetValue(null);
}
}
}
return default(T);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment