Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get int value from enum in C#

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public enum Question {     Role = 2,     ProjectFunding = 3,     TotalEmployee = 4,     NumberOfServers = 5,     TopBusinessConcern = 6 } 

In the Questions class I have a get(int foo) function that returns a Questions object for that foo. Is there an easy way to get the integer value off the enum so I can do something like this Questions.Get(Question.Role)?

like image 989
jim Avatar asked Jun 03 '09 06:06

jim


People also ask

How do you find the int value of an enum?

You can use: int i = Convert. ToInt32(e); int i = (int)(object)e; int i = (int)Enum.

Can enum have int values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

What is enum number?

Numeric Enum Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.

How do you convert enum to int in Python?

Use the IntEnum class from the enum module to convert an enum to an integer in Python. You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.


2 Answers

Just cast the enum, e.g.

int something = (int) Question.Role; 

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649}; 

you should use

long something = (long)StarsInMilkyWay.Wolf424B; 
like image 156
Tetraneutron Avatar answered Oct 03 '22 03:10

Tetraneutron


Since Enums can be any integral type (byte, int, short, etc.), a more robust way to get the underlying integral value of the enum would be to make use of the GetTypeCode method in conjunction with the Convert class:

enum Sides {     Left, Right, Top, Bottom } Sides side = Sides.Bottom;  object val = Convert.ChangeType(side, side.GetTypeCode()); Console.WriteLine(val); 

This should work regardless of the underlying integral type.

like image 34
cecilphillip Avatar answered Oct 03 '22 05:10

cecilphillip