Created
October 6, 2016 08:11
-
-
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.
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 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