2

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

StackTrace
  • 9,190
  • 36
  • 114
  • 202

1 Answers1

2

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

Amit Kotha
  • 1,641
  • 1
  • 11
  • 16