Home > Backend Development > C++ > How Can I Get Integer Values from C# Enums?

How Can I Get Integer Values from C# Enums?

Patricia Arquette
Release: 2025-01-28 12:51:10
Original
751 people have browsed it

How Can I Get Integer Values from C# Enums?

Get the integer value from C#enumeration

Improve the get function in the "Questions" class

In the "Questions" class, you try to design a "Get" function that will retrieve an "Questions" object for the integer value provided. However, in order to facilitate this retrieval, you need a way to extract the integer value from the "Question" enumeration.

Solution: Type conversion

The easiest way to retrieve the most simple value of enumeration is to convert the enumeration into a underlying data type. In most cases, enumeration uses "int" as its underlying data type. Therefore, you can convert the enumeration value into an integer through the mandatory conversion, as shown below:

This forced conversion will provide you with an integer value associated with the "Role" enumeration value, which is 2 in this example.

<code class="language-csharp">int roleValue = (int)Question.Role;</code>
Copy after login
alternative type

Although "int" is converted to "int" is usually enough to meet most enumeration needs, it is worth noting that enumeration can also use different underlying data type definitions, such as "UINT", "Long" or "Ulong, Ulong, Ulong, "" ". In this case, you should convert an enumeration into an appropriate type to accurately retrieve the value. For example, if the enumeration named "Starsinmilkyway" uses "Long" as its underlying type definition:

To retrieve the "wolf424b" value as an integer, you need to convert it to "Long":

The above is the detailed content of How Can I Get Integer Values from C# Enums?. 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