C# Tips and Tricks #2 – How to Get the Description Attribute Value of Enum in C# ?

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);

image

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();
        }

    }
    
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...