Skip to content

Instantly share code, notes, and snippets.

@avianbc
Created May 22, 2019 23:47
Show Gist options
  • Save avianbc/488c6b17a3e2e52ea4ad2389a52870e1 to your computer and use it in GitHub Desktop.
Save avianbc/488c6b17a3e2e52ea4ad2389a52870e1 to your computer and use it in GitHub Desktop.
Enum friendly names via DisplayAttribute + DescriptionAttribute
public static class ExtensionMethods
{
/// <summary>
/// Returns friendly name for enum as long as enum is decorated with a Display or Description Attribute, otherwise returns Enum.ToString()
/// </summary>
/// <param name="value">Enum</param>
/// <returns>Friendly name via DescriptionAttribute</returns>
public static string ToFriendlyName(this Enum value)
{
Type type = value.GetType();
// first, try to get [Display(Name="")] attribute and return it if exists
string displayName = TryGetDisplayAttribute(value, type);
if (!String.IsNullOrWhiteSpace(displayName))
{
return displayName;
}
// next, try to get a [Description("")] attribute
string description = TryGetDescriptionAttribute(value, type);
if (!String.IsNullOrWhiteSpace(description))
{
return description;
}
// no attributes found, just tostring the enum :(
return value.ToString();
}
private static string TryGetDescriptionAttribute(Enum value, Type type)
{
if (!type.IsEnum) throw new ArgumentException(String.Format("Type '{0}' is not Enum", type));
string name = Enum.GetName(type, value);
if (!String.IsNullOrWhiteSpace(name))
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
private static string TryGetDisplayAttribute(Enum value, Type type)
{
if (!type.IsEnum) throw new ArgumentException(String.Format("Type '{0}' is not Enum", type));
MemberInfo[] members = type.GetMember(value.ToString());
if (members.Length > 0)
{
MemberInfo member = members[0];
var attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes.Length > 0)
{
DisplayAttribute attribute = (DisplayAttribute)attributes[0];
return attribute.GetName();
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment