There are times when you want to get the attributes of the enum values from your C# code for some display purpose .
For example , consider the below enum Named “EmployeeDesignation”.
public enum EmployeeDesignation { TechnicalLead, SolutionArchitect, SeniorSoftwareEngineer }
You might want to display the enum value with out space for display purposes. You can achieve it by adding the description attribute as shown below.
public enum EmployeeDesignation { [Description("Technical Lead")] TechnicalLead, [Description("Solution Architect")] SolutionArchitect, [Description("Senior Software Engineer")] SeniorSoftwareEngineer }
To display the values on the UI , now we can use the values available in the description attribute rather than the enum value itself.
How to Get the Description Attribute of Enum in C# ?
Below is a code snippet on how to get the value present in the description attribute and display in the console.
How to Get the Description Attribute Value of Enum in C# ?
var enumType = typeof(EmployeeDesignation); var memberData = enumType.GetMember(EmployeeDesignation.SolutionArchitect.ToString()); var Description = (memberData[0].GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute).Description; Console.WriteLine(Description);
Below is the complete code snippet that was used for the demo.
using System; using System.ComponentModel; using System.Linq; namespace DeveloperPublishApp { class Program { public enum EmployeeDesignation { [Description("Technical Lead")] TechnicalLead, [Description("Solution Architect")] SolutionArchitect, [Description("Senior Software Engineer")] SeniorSoftwareEngineer } static void Main(string[] args) { var enumType = typeof(EmployeeDesignation); var memberData = enumType.GetMember(EmployeeDesignation.SolutionArchitect.ToString()); var Description = (memberData[0].GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute).Description; Console.WriteLine(Description); Console.ReadLine(); } } }