Udemy

User Friendly Display Text For Enum in C#

Wednesday, June 10, 2015 0 Comments A+ a-

When using Enum sometime we dont want to show the enum name that we have in code to user but instead of that we want to show some text that is understanable for end user.I will share today how we can set display text on Enum values that we can use to show to end-user.

Consider this Enum:


public enum eUserRole : int
 {
    SuperAdmin = 0,
    PhoenixAdmin = 1,
    OfficeAdmin = 2,
    ReportUser = 3,
    BillingUser = 4
  }



So, it is obvious that one would not like to show user SuperAdmin in this way without space, one would expect it to be displayed like "Super Admin" at front end.


For that first of all we will have to create a custom DisplayName attribute for Enum:

public class EnumDisplayNameAttribute : Attribute
{
  private string _displayName;
  public string DisplayName
  {
      get { return _displayName; }
      set { _displayName = value; }
  }
}

Now we can use this attribute to decorate it on our Enum values:

public enum eUserRole : int
{
    [EnumDisplayName(DisplayName="Super Admin")]
    SuperAdmin = 0,
    [EnumDisplayName(DisplayName = "Phoenix Admin")]
    PhoenixAdmin = 1,
    [EnumDisplayName(DisplayName = "Office Admin")]
    OfficeAdmin = 2,
    [EnumDisplayName(DisplayName = "Report User")]
    ReportUser = 3,
    [EnumDisplayName(DisplayName = "Billing User")]
    BillingUser = 4
}

For getting the DisplayName atttribute we have wrote an extension method on Enum which will return us the DisplayName attribute value:


public static class EnumExtensions
{

   public static string DisplayName(this Enum value)
   {
       FieldInfo field = value.GetType().GetField(value.ToString());

       EnumDisplayNameAttribute attribute
               = Attribute.GetCustomAttribute(field, typeof(EnumDisplayNameAttribute))
                   as EnumDisplayNameAttribute;

       return attribute == null ? value.ToString() : attribute.DisplayName;
   }
}
and now we can call it on Enum values to get the DisplayName attribute value simply:


      Console.WriteLine(eUserRole.SuperAdmin.DisplayName());


This will output on Console:

           Super Admin 
Coursera - Hundreds of Specializations and courses in business, computer science, data science, and more