Skip to content

Instantly share code, notes, and snippets.

@danielmackay
Last active December 21, 2015 18:59
Show Gist options
  • Save danielmackay/6350828 to your computer and use it in GitHub Desktop.
Save danielmackay/6350828 to your computer and use it in GitHub Desktop.
Helper functions for pulling attributes from enums. #enum
/// <summary>
/// A helper class which helps conversion between enum and code.
/// </summary>
public static class EnumExt
{
/// <summary>
/// Get a description of Enum
/// </summary>
/// <param name="value">Enum value</param>
/// <returns>description</returns>
public static string GetDescription(this Enum value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
return attributes[0].Description;
return value.ToString();
}
/// <summary>
/// Get a description of Enum
/// </summary>
/// <param name="value">Enum value</param>
/// <returns>description</returns>
public static string GetDisplayName(this Enum value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
var attributes = (DisplayAttribute[])fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes.Length > 0)
return attributes[0].Name;
return value.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment