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 from the enum so I can do something like Questions.Get(Question.Role)
?
To ensure an enum value exists and then parse it, you can also do the following.
I hope this helps.
Declare it as a static class having public constants:
And then you can reference it as
Question.Role
, and it always evaluates to anint
or whatever you define it as.If you want to get an integer for the enum value that is stored in a variable, wich the type would be
Question
, to use for example in a method, you can simply do this I wrote in this example:This will change the window title to 4 because the variable
Geselecteerd
isTalen.Nederlands
. If I change it toTalen.Portugees
and call the method again, the text will change to 3.I had a hard time finding this simple solution on the internet and I couldn't find it, so I was testing something and found this out. Hope this helps. ;)
One more way to do it:
Will result in:
On a related note, if you want to get the
int
value fromSystem.Enum
, then givene
here:You can use:
The last two are plain ugly. I prefer the first one.
I have recently converted away from using enums in my code in favour of instead using classes with protected constructors and predefined static instances (thanks to Roelof - C# Ensure Valid Enum Values - Futureproof Method).
In light of that, below's how I'd now approach this issue (including implicit conversion to/from
int
).The advantage of this approach is you get everything you would have from the enum, but your code's now much more flexible, so should you need to perform different actions based on the value of
Question
, you can put logic intoQuestion
itself (i.e. in the preferred OO fashion) as opposed to putting lots of case statements throughout your code to tackle each scenario.NB: Answer updated 2018-04-27 to make use of C# 6 features; i.e. declaration expressions and lambda expression body definitions. See revision history for original code. This has the benefit of making the definition a little less verbose; which had been one of the main complaints about this answer's approach.