Home >Backend Development >C++ >How to Get an Enum's Description from its Integer Value in C#?
Accessing Enum Descriptions from Integer Values in C#
This guide demonstrates how to obtain the descriptive text associated with an enum member using its integer representation in C#. The core functionality relies on a helper method:
Here's a static method, GetEnumDescription
, designed to retrieve the description:
<code class="language-csharp">public static string GetEnumDescription(Enum value) { var fi = value.GetType().GetField(value.ToString()); var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); return attributes != null && attributes.Length > 0 ? attributes[0].Description : value.ToString(); }</code>
This method efficiently extracts the DescriptionAttribute
if present; otherwise, it returns the enum member's name.
To use this method with an integer value, simply cast the integer to your enum type:
<code class="language-csharp">int intValue = 1; string description = Enumerations.GetEnumDescription((MyEnum)intValue);</code>
This code snippet casts intValue
to MyEnum
before passing it to GetEnumDescription
, thus retrieving the description corresponding to the enum member with the integer value 1. This approach provides a clean and efficient way to access the descriptive text of enum members using their integer equivalents.
The above is the detailed content of How to Get an Enum's Description from its Integer Value in C#?. For more information, please follow other related articles on the PHP Chinese website!