Home >Backend Development >C++ >How Can I Easily Retrieve the Integer Value of a C# Enum?

How Can I Easily Retrieve the Integer Value of a C# Enum?

Linda Hamilton
Linda HamiltonOriginal
2025-01-28 12:56:09897browse

How Can I Easily Retrieve the Integer Value of a C# Enum?

Get an integer value in C#

C#enumeration is used to define a group of naming constants. By default, enumeration has an integer value assigned to them. However, direct access to these values ​​may be troublesome, especially when dealing with objects.

Question:

Consider a class called Questions

, which contains a enumeration called

Question . QUESTION Epolume contains an integer value that represents different types of problems: In the Questions

class, you have a method called
<code class="language-c#">public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}</code>
Get (int FOO)

, which returns the Questions object according to the integer value provided. Is there a simple way to convert the enumeration value (such as Question.role ) to an integer so that you can directly call the Get method? Answer:

Yes, there is a simple way to retrieve the integer value from the enumeration in C#. You can simply convert an enumeration to an integer:

In this case,

ROLEVALUE

Set to 2, which is the integer value assigned to

Role
<code class="language-c#">int roleValue = (int)Question.Role;</code>
enumerated.

Note: By default, the enumeration integer is used as its underlying type. However, you can specify different underlying types, such as long integer or non -symbolic integer. If your enumeration has different underlying types, it should be converted to the corresponding type when retrieved the value.

The above is the detailed content of How Can I Easily Retrieve the Integer Value of a C# Enum?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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