Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Enum Index value in C#

Tags:

c

c#

enums

integer

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#?

like image 387
Shamim Hafiz - MSFT Avatar asked Jun 02 '11 10:06

Shamim Hafiz - MSFT


People also ask

How do you find the index of an enum?

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!

What is the value of enum in C?

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.

What is the syntax of enum?

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.

What is typedef enum in C programming?

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.


1 Answers

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.

like image 96
Iain Ward Avatar answered Sep 17 '22 05:09

Iain Ward