I\'ve got a property in my model called \"Promotion\" that its type is a flag enum called \"UserPromotion\". Members of my enum have display attributes set as follows:
Building on Todd's great answer which built on Aydin's great answer, here's a generic extension method that doesn't require any type parameters.
///
/// Gets human-readable version of enum.
///
/// DisplayAttribute.Name property of given enum.
public static string GetDisplayName(this T enumValue) where T : IComparable, IFormattable, IConvertible
{
if (!typeof(T).IsEnum)
throw new ArgumentException("Argument must be of type Enum");
DisplayAttribute displayAttribute = enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute();
string displayName = displayAttribute?.GetName();
return displayName ?? enumValue.ToString();
}
I needed this for my project because something like the below code, where not every member of the enum has a DisplayAttribute
, does not work with Todd's solution:
public class MyClass
{
public enum MyEnum
{
[Display(Name="ONE")]
One,
// No DisplayAttribute
Two
}
public void UseMyEnum()
{
MyEnum foo = MyEnum.One;
MyEnum bar = MyEnum.Two;
Console.WriteLine(foo.GetDisplayName());
Console.WriteLine(bar.GetDisplayName());
}
}
// Output:
//
// ONE
// Two
If this is a complicated solution to a simple problem, please let me know, but this was the fix I used.