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
- }
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;
- }
- }
- }
- 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
- }
- 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;
- }
- }
- Console.WriteLine(eUserRole.SuperAdmin.DisplayName());
Super Admin

Ehsan SajjadPosted Jan 11, 2016, 12:44 PM
Thanks for compliment
Ranjan SrivastavaPosted Dec 31, 2015, 6:04 AM
Super ..
Santhakumar MunuswamyPosted Dec 27, 2015, 9:07 AM
Nice share