tags:

views:

7510

answers:

5

I have a class called Questions, in this class is an enum called question which looks like this.

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

In the Question class I have a get(int foo) function that returns a Question 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)?

+7  A: 
Question question = Question.Role;
int value = (int) question;

Will result in value == 2.

jerryjvl
The temporary variable question is unnecessary.
Gishu
So something like this Questions.Get(Convert.ToInt16(Question.Applications))
jim
no need to convert it - just cast.
Michael Petrotta
You can simply cast in either direction; the only thing to watch is that enums don't enforce anything (the enum value could be 288, even though no Question exists with that number)
Marc Gravell
@jim: No, just cast the value: Questions.Get((int)Question.Applications);
Guffa
@Gishu: I know, but I prefer being verbose and clear ;)
jerryjvl
thanks everyone...I just want to be clear...casting Question.Role returns 2, the value and not 1 the index...correct?
jim
@jim: that's correct.
Michael Petrotta
(though it'd be 0 for the index, but that's neither here nor there)
Michael Petrotta
Thanks guys...the stackoverflow community is truly awesome.
jim
+32  A: 

Just cast the enum eg.

int something = (int)Question.Role;
Tetraneutron
+3  A: 

It's easier than you think - your enum is already an int. It just needs to be reminded:

int y = (int)Question.Role;
Console.WriteLine(y); // prints 2

EDIT: Every enumeration type has an underlying type, which can be any integral type except char.

Michael Petrotta
Nitpick: *this* enum is already an int. Other enums might be different types -- try "enum SmallEnum : byte { A, B, C }"
mquander
Absolutely true. C# reference: "Every enumeration type has an underlying type, which can be any integral type except char."
Michael Petrotta
+2  A: 

Example

Public Enum EmpNo
{
Raj=1
Rahul,
Priyanka
}

And in the code behind to get enum value

int setempNo=(int)EmpNo.Raj; //this will give setempNo=1

or

int setempNo=(int)EmpNo.Rahul; //this will give setempNo=2

Enums will increment by 1; you can set the start value. else it will be assigned as 0 initially.

sooraj
+1  A: 

Since Enums can be any integral type (short, byte, int ...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;

var val = Convert.ChangeType(side, side.GetTypeCode()) ;
Console.WriteLine(val);

This should work regardless of the underlying integral type type.

cecilphillip