How to get the Enum Index value in C# How to get the Enum Index value in C# c c

How to get the Enum Index value in C#


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.


Another way to convert an Enum-Type to an int:

enum E{    A = 1,   /* index 0 */    B = 2,   /* index 1 */    C = 4,   /* index 2 */    D = 4    /* index 3, duplicate use of 4 */}void Main(){    E e = E.C;    int index = Array.IndexOf(Enum.GetValues(e.GetType()), e);    // index is 2    E f = (E)(Enum.GetValues(e.GetType())).GetValue(index);    // f is  E.C}

More complex but independent from the INT values assigned to the enum values.


By default the underlying type of each element in the enum is integer.

enum Values{   A,   B,   C}

You can also specify custom value for each item:

enum Values{   A = 10,   B = 11,   C = 12}int x = (int)Values.A; // x will be 10;

Note: By default, the first enumerator has the value 0.