Skip to content

Instantly share code, notes, and snippets.

@mirsaeedi
Created October 6, 2016 08:11
Show Gist options
  • Save mirsaeedi/9158229d7b3c367a88a29472ef51a78e to your computer and use it in GitHub Desktop.
Save mirsaeedi/9158229d7b3c367a88a29472ef51a78e to your computer and use it in GitHub Desktop.
An extension method which helps you to get the value of DisplayAttribute of an enum member.
public static string GetEnumDisplayName(this Enum value,string unknownValue="Unknown")
{
if(value == null)
{
return unknownValue;
}
var type = value.GetType();
if (!type.IsEnum) throw new ArgumentException(String.Format("Type '{0}' is not Enum", type));
var members = type.GetMember(value.ToString());
if (members.Length == 0) throw new ArgumentException(String.Format("Member '{0}' not found in type '{1}'", value, type.Name));
var member = members[0];
var attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes.Length == 0) throw new ArgumentException(String.Format("'{0}.{1}' doesn't have DisplayAttribute", type.Name, value));
var attribute = (DisplayAttribute)attributes[0];
return attribute.GetName();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment