Created
May 22, 2019 23:47
-
-
Save avianbc/488c6b17a3e2e52ea4ad2389a52870e1 to your computer and use it in GitHub Desktop.
Enum friendly names via DisplayAttribute + DescriptionAttribute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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