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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...