SoFunction
Updated on 2025-03-07

How to get the description attribute of enumeration in C# Detailed explanation

Preface

Enumeration provides very good support for me to see the readability of daily development, but sometimes when using enum types, we need to take the name and value, and sometimes we even need to take the description of the enum type. Through reflection, we can obtain the description attribute of the enum type.

First of all, we need to add a description attribute to the enum type (it is impossible to obtain if there is no attribute). [Description] is the description attribute. Using this attribute, we need to add a using reference.

public enum EnumSex
{
  /// <summary>
  /// male  /// </summary>
  [Description("male")]
  Male = 0,
  /// <summary>
  /// female  /// </summary>
  [Description("female")]
  Female = 1
}

Next we need to write a method to obtain the description attribute. FieldInfo needs to add a using reference, DescriptionAttribute needs to add a using reference.

public string GetEnumDescription(Enum enumValue)
{
  string value = ();
  FieldInfo field = ().GetField(value);
  object[] objs = (typeof(DescriptionAttribute), false);  //Get description attribute  if (objs == null ||  == 0)  //When the description attribute does not have it, return the name directly    return value;
  DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
  return ;
}

OK, now we can get the description of the enum.

string sex = GetEnumDescription(); //sex = "female"

Similarly, we can assign other types of attributes to the enum type, such as Obsolete. In the GetEnumDescription method, we can also get the attributes.

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.