How to get the Display Name Attribute of an Enum member in C# ?
Riya Answered question December 19, 2023
To get the display name attribute of an enum member in C# without providing the actual code:
- Use reflection to access metadata of the enum.
- Check if the
Displayattribute is present on the enum member. - If the attribute is present, retrieve the display name associated with that enum member.
This approach allows you to dynamically access the display names defined for enum members without hardcoding them.
Riya Answered question December 19, 2023
- Create an enum with a DisplayAttribute on one of its members. For example:
public enum Color
{
    [Display(Name = "Red")]
    Red,
    [Display(Name = "Green")]
    Green,
    [Display(Name = "Blue")]
    Blue
}
- Use theÂ
GetCustomAttribute()Â method to get the DisplayAttribute for the enum member. For example:
var enumMember = Color.Red; var displayAttribute = enumMember.GetType().GetCustomAttribute(typeof(DisplayAttribute));
- TheÂ
displayAttribute variable will now contain the DisplayAttribute for the enum member. You can then get theÂName property of the DisplayAttribute to get the display name of the enum member. For example:
var displayName = displayAttribute.Name;
Here is an example of the complete code:
public enum Color
{
    [Display(Name = "Red")]
    Red,
    [Display(Name = "Green")]
    Green,
    [Display(Name = "Blue")]
    Blue
}
 public static void Main()
{
    var enumMember = Color.Red;
    var displayAttribute = enumMember.GetType().GetCustomAttribute(typeof(DisplayAttribute));
    var displayName = displayAttribute.Name;
    Console.WriteLine(displayName); // Red
}
admin Answered question August 4, 2023
