get enum description attribute in csharp

To get the description attribute of an enum value in C#, you can use reflection to access the attribute and retrieve its value. Here's an example code block:

main.cs
using System;
using System.ComponentModel;
using System.Reflection;

public enum MyEnum
{
    [Description("This is the first option")]
    FirstOption,
    [Description("This is the second option")]
    SecondOption,
    [Description("This is the third option")]
    ThirdOption
}

class MyProgram
{
    static void Main()
    {
        MyEnum option = MyEnum.SecondOption;

        // Get the enum field
        FieldInfo field = option.GetType().GetField(option.ToString());

        // Get the description attribute value
        DescriptionAttribute attribute = field.GetCustomAttribute<DescriptionAttribute>();
        string description = attribute.Description;

        Console.WriteLine(description); // Outputs "This is the second option"
    }
}
757 chars
31 lines

In this example, we have an enum MyEnum with three values that have associated description attributes. We retrieve the description attribute value for a specific enum value option using reflection. The GetField method is used to get a FieldInfo object for the enum value, and then the GetCustomAttribute<DescriptionAttribute> method is used to retrieve the DescriptionAttribute object associated with that field. From the attribute object, we can then get the Description property value.

gistlibby LogSnag