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.
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.
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.
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!