C# Tip Article
How to display custom string for enum value
How can we show user-defined string for enum value? For example, want to display "Standard Card" for CardType.StandardCard.
public enum CardType
{
StandardCard = 1,
SilverCard = 2,
GoldCard = 3,
}
One way of doing it is to make use of DisplayAttribute in System.ComponentModel.DataAnnotations namespace. Add [Display(Name="")] attribute to each enum member.
public enum CardType
{
[Display(Name = "Standard Card")]
StandardCard = 1,
[Display(Name = "Silver Card")]
SilverCard = 2,
[Display(Name = "Gold Card")]
GoldCard = 3,
}
And then, add an extension method for Enum type. In the extension method, we can use .NET reflection to retrieve the custom attribute (DisplayAttribute).
using System.ComponentModel.DataAnnotations; //for DisplayAttribute
public static class Extensions
{
public static string ToDisplayName(this Enum en)
{
var attrs = en.GetType()
.GetMember(en.ToString())
.Single()
.GetCustomAttributes(typeof(DisplayAttribute), false);
return ((DisplayAttribute)attrs[0]).Name;
}
}
Once the extension method is defined, we can simply call enum.ToDisplayName().
string strCard = CardType.StandardCard.ToDisplayName();
