In C, enums
, internally equates to an integer. Therefore we can treat data types of enum
as integer also.
How to achieve the same with C#?
Assuming it's an int , you can do it like this: int eValue = (int)enumValue; However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order!
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
The keyword “enum” is used to declare an enumeration. Here is the syntax of enum in C language, enum enum_name{const1, const2, ....... }; The enum keyword is also used to define the variables of enum type.
A typedef is a mechanism for declaring an alternative name for a type. An enumerated type is an integer type with an associated set of symbolic constants representing the valid values of that type.
Firstly, there could be two values that you're referring to:
Underlying Value
If you are asking about the underlying value, which could be any of these types: byte, sbyte, short, ushort, int, uint, long or ulong
Then you can simply cast it to it's underlying type. Assuming it's an int
, you can do it like this:
int eValue = (int)enumValue;
However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order! (Credit to @JohnStock for the poke to clarify).
This example assigns each a new value, and show the value returned:
public enum MyEnum { MyValue1 = 34, MyValue2 = 27 } (int)MyEnum.MyValue2 == 27; // True
Index Value
The above is generally the most commonly required value, and is what your question detail suggests you need, however each value also has an index value (which you refer to in the title). If you require this then please see other answers below for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With