patterncsharpCritical
Get int value from enum in C#
Viewed 0 times
enumfromintvalueget
Problem
I have a class called
In the
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)?Solution
Just cast the enum, e.g.
The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is
However, as cecilphillip points out, enums can have different underlying types.
If an enum is declared as a
you should use
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. forenum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};you should use
long something = (long)StarsInMilkyWay.Wolf424B;Code Snippets
int something = (int) Question.Role;enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};long something = (long)StarsInMilkyWay.Wolf424B;Context
Stack Overflow Q#943398, score: 3030
Revisions (0)
No revisions yet.