Retrieve enum description from value in C#
In C#, enumerations can be decorated using the Description attribute, allowing you to associate a meaningful description with each enumeration member. To retrieve the description of a given enumeration value, you can utilize the GetEnumDescription() method as follows:
<code class="language-csharp">public enum MyEnum { Name1 = 1, [Description("Here is another")] HereIsAnother = 2, [Description("Last one")] LastOne = 3 } public static string GetEnumDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; return attributes?.Any() == true ? attributes.First().Description : value.ToString(); }</code>
Suppose you want to retrieve the description of a specific enumeration value, represented as an integer (e.g., 1). You can use a cast to convert this integer to an enumeration value before passing it to the GetEnumDescription() method:
<code class="language-csharp">int value = 1; string description = GetEnumDescription((MyEnum)value);</code>
By casting an integer to the corresponding enumeration type, you can retrieve the associated description of the corresponding enumeration member.
The above is the detailed content of How to Retrieve a C# Enum's Description from its Integer Value?. For more information, please follow other related articles on the PHP Chinese website!