User Friendly Display Text For Enum in C#

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:

  1. public enum eUserRole: int  
  2. {  
  3.     SuperAdmin = 0,  
  4.         PhoenixAdmin = 1,  
  5.         OfficeAdmin = 2,  
  6.         ReportUser = 3,  
  7.         BillingUser = 4  
  8. }  
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:
  1. public class EnumDisplayNameAttribute: Attribute   
  2. {  
  3.     private string _displayName;  
  4.     public string DisplayName  
  5.     {  
  6.         get   
  7.         {  
  8.             return _displayName;  
  9.         }  
  10.         set   
  11.         {  
  12.             _displayName = value;  
  13.         }  
  14.     }  
  15. }  
Now we can use this attribute to decorate it on our Enum values:
  1. public enum eUserRole: int   
  2. {  
  3.     [EnumDisplayName(DisplayName = "Super Admin")]  
  4.     SuperAdmin = 0, [EnumDisplayName(DisplayName = "Phoenix Admin")]  
  5.     PhoenixAdmin = 1, [EnumDisplayName(DisplayName = "Office Admin")]  
  6.     OfficeAdmin = 2, [EnumDisplayName(DisplayName = "Report User")]  
  7.     ReportUser = 3, [EnumDisplayName(DisplayName = "Billing User")]  
  8.     BillingUser = 4  
  9. }  
For getting the DisplayName atttribute we have wrote an extension method on Enum which will return us the DisplayName attribute value:
  1. public static class EnumExtensions   
  2. {  
  3.   
  4.     public static string DisplayName(this Enum value)  
  5.   {  
  6.         FieldInfo field = value.GetType().GetField(value.ToString());  
  7.   
  8.         EnumDisplayNameAttribute attribute  
  9.             = Attribute.GetCustomAttribute(field, typeof(EnumDisplayNameAttribute))  
  10.         as EnumDisplayNameAttribute;  
  11.   
  12.         return attribute == null ? value.ToString() : attribute.DisplayName;  
  13.     }  
  14. }  
and now we can call it on Enum values to get the DisplayName attribute value simply:
  1. Console.WriteLine(eUserRole.SuperAdmin.DisplayName());  
This will output on Console:

Super Admin