Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Enum display name [duplicate]

Tags:

c#

I have an emun defined as in the sample below.

 public enum SampleEnum : int
{
    [Display(Name = "One")]
    Test_One = 1,
    [Display(Name = "Two")]
    Test_Two = 2,
    [Display(Name = "Three")]
    Test_Three = 3

}

In the below line of code, how can get the Display instead name?

   var displayName = Enum.GetName(typeof(SampleEnum ), 2); 

In the above line, i would like to get Two instead of Test_Two

like image 280
StackTrace Avatar asked Sep 12 '25 15:09

StackTrace


1 Answers

You can create Extension method for the same.

   public static class EnumExtensions
      {
        public static string GetDisplayName(this Enum enumValue)
        {
          return enumValue.GetType()
            .GetMember(enumValue.ToString())
            .First()
            .GetCustomAttribute<DisplayAttribute>()
            ?.GetName();
        }
      }

https://dnilvincent.com/blog/posts/how-to-get-enum-display-name-in-csharp-net

like image 146
Amit Kotha Avatar answered Sep 14 '25 09:09

Amit Kotha