Accessing the Integer Value of a C# Enum Member
C# enums offer a user-friendly way to define a set of named constants. Sometimes, you need to access the integer value underlying an enum member. This example demonstrates how to retrieve the integer representation of an enum member, such as Question.Role
within a Questions
class.
The simplest approach, assuming the enum's underlying type is the default int
, involves a direct cast:
<code class="language-csharp">int value = (int)Question.Role;</code>
This directly converts the enum member to its integer equivalent. However, remember that enums can be defined with other underlying types like uint
, long
, or ulong
.
If your enum uses a non-default underlying type, for instance:
<code class="language-csharp">enum StarsInMilkyWay : uint { ... };</code>
You'll need to use the appropriate cast to get the correct integer value:
<code class="language-csharp">uint value = (uint)StarsInMilkyWay.Wolf424B;</code>
These methods provide a straightforward way to obtain and utilize the integer values associated with your enum members in various programming contexts.
The above is the detailed content of How Do I Retrieve the Integer Value of a C# Enum Member?. For more information, please follow other related articles on the PHP Chinese website!