Home > Backend Development > C++ > How to Retrieve a C# Enum's Description from its Integer Value?

How to Retrieve a C# Enum's Description from its Integer Value?

Susan Sarandon
Release: 2025-01-24 20:26:11
Original
447 people have browsed it

How to Retrieve a C# Enum's Description from its Integer Value?

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

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

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!

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