Home >Backend Development >C++ >How Do I Convert Enum Constants to Their Underlying Integer Values in C#?

How Do I Convert Enum Constants to Their Underlying Integer Values in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-28 12:46:11372browse

How Do I Convert Enum Constants to Their Underlying Integer Values in C#?

Accessing the Underlying Integer Value of C# Enums

C# enums are typically based on integers, offering a simple way to retrieve their numerical representation. This is especially helpful when using enums as array indices or in calculations.

Direct Casting for Standard Enums

The most common approach involves directly casting the enum constant to an int:

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

This works flawlessly for enums with the default integer backing type.

Handling Non-Integer Enum Types

However, enums can also be defined with underlying types like uint, long, or ulong. In such cases, casting to the correct type is essential. For example:

<code class="language-csharp">enum StarsInMilkyWay : long { Sun = 1, V645Centauri = 2, ..., Wolf424B = 2147483649 };

long wolf424BValue = (long)StarsInMilkyWay.Wolf424B;</code>

Here, we cast StarsInMilkyWay.Wolf424B to long to obtain its underlying long integer value.

Conclusion

Using appropriate casting, you can easily access the numerical value of any enum constant, expanding the usability of enums in your C# code. Remember to match the cast type to the enum's underlying type declaration.

The above is the detailed content of How Do I Convert Enum Constants to Their Underlying Integer Values in C#?. 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