Get display name of an enum in C#

This is a simple code to get the display name of an enum in C#. Sometimes we need a proper name, not the property names of the enum. The code below gives us the display name of an enum in c#.

A sample enum could be like this:


public enum UserType
{
[Display(Name = "Administrator")]
Admin,
[Display(Name = "Compliance Officer")]
Compliance,
[Display(Name = "HR & Accounts")]
Hr
}

To get the display name-


public string GetDisplayName(this object val)
{
return val.GetType().GetMember(val.ToString())
.FirstOrDefault()?.GetCustomAttribute(false)?.Name ??
(val.ToString() == "0" ? "" : val.ToString());
}

It gets the custom attribute- “Display Attribute” to get the display name of the enum.