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)
?
You can use: int i = Convert. ToInt32(e); int i = (int)(object)e; int i = (int)Enum.
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.
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.
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.
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;
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.
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