Home > Backend Development > C++ > How to Get an Enum's Description from its Integer Value in C#?

How to Get an Enum's Description from its Integer Value in C#?

Mary-Kate Olsen
Release: 2025-01-24 20:46:11
Original
484 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template