The name of an enum in c# can't contain any special characters or spaces. For example, the third value in this enum won't work:
public enum Soda : int
{
SevenUp = 0,
Sprite = 1,
Dr. Pepper = 2 // This will not work
}
Add Display Name Attribute
Adding a Display Name attribute to the enum values allows us to use spaces and special characters:
public enum Soda : int
{
SevenUp = 0,
Sprite = 1,
[Display(Name = "Dr. Pepper")]
DrPepper = 2
}
Read The Attribute
In ASP.Net Core:
To get the display name in ASP.Net Core, you can take advantage of one of the HTML helper methods, e.g. @Html.EnumDropDownListFor(model=>model.Soda)
.
Anywhere in a C# Project:
And to get the display name anywhere in a C# project, you can add an enum extension class that returns the display name property. If the property is missing (like it is for the first two enum values above), it falls back to the string equivalent.
EnumExtensions.cs:
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enumValue)
{
string displayName;
displayName = enumValue.GetType()
.GetMember(enumValue.ToString())
.FirstOrDefault()
.GetCustomAttribute<DisplayAttribute>()?
.GetName();
if (String.IsNullOrEmpty(displayName))
{
displayName = enumValue.ToString();
}
return displayName;
}
}
Read the attribute using the extension method:
Soda.DrPepper.GetDisplayName();
Credits
I used the following two StackOverflow answers to help me put together the enum extension class above:
https://stackoverflow.com/a/26455406/4669143
https://stackoverflow.com/a/28525614/4669143