How to get the description of an enum in C#?

This simple code shows how to get the description of an enum in C#.

A sample enum could be-

public enum Colors{
[Description("Green but not so much!")]
Greenish,
[Description("Sky Blue")]
SkyBlue,
[Description("Blood Red")]
Blood Red
}

This below code gets the description of the enum-

public string GetEnumDescription(object val)
{
return
val.GetType()
.GetMember(val.ToString())
.FirstOrDefault()?.GetCustomAttribute<DescriptionAttribute>(false)?.Description ??
(val.ToString() == "0" ? "" : val.ToString());
}

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.