Home > Backend Development > C++ > How to Retrieve Enum Descriptions from Integer Values in C#?

How to Retrieve Enum Descriptions from Integer Values in C#?

Mary-Kate Olsen
Release: 2025-01-24 20:38:13
Original
189 people have browsed it

How to Retrieve Enum Descriptions from Integer Values in C#?

Retrieve enumeration description from value in C#

Problem Statement:

Consider an enumeration whose members are assigned the Description property:

<code class="language-c#">public enum MyEnum
{
    Name1 = 1,
    [Description("Here is another")]
    HereIsAnother = 2,
    [Description("Last one")]
    LastOne = 3
}</code>
Copy after login

Goal: Get the description of the association from the given enumeration value (e.g., for value 2, get "Here is another").

Proposed solution:

Use the GetEnumDescription() method:

<code class="language-c#">public static string GetEnumDescription(Enum value)
{
    // ... (与问题陈述中提供的代码相同)
}</code>
Copy after login

Retrieve description from integer value:

To get a description from an integer value representing an enumeration, cast the value to the corresponding enumeration type:

<code class="language-c#">int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);</code>
Copy after login

Explanation:

In C#, enumerations essentially use integers as their underlying data type. By casting an integer value to an enumeration type, you actually convert it to the corresponding enumeration value, allowing you to pass it to the GetEnumDescription() method and retrieve the assigned description.

The above is the detailed content of How to Retrieve Enum Descriptions from Integer Values 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