12

If I have this code

//Spice Enums
enum SpiceLevels {None = 0 , Mild = 1, Moderate = 2, Ferocious = 3};

Which states the Enum Names + Their Number, how can I call an enum from a variable, say if a variable was 3, how do I get it to call and display Ferocious?

Julian
  • 33,915
  • 22
  • 119
  • 174
MarsBars9459
  • 157
  • 1
  • 1
  • 7
  • As answered you can just cast the `int` value. But keep in mind that an `enum` can have multiple times the same value. In this case, the first element would be returned. – Arthur Rey Jan 15 '17 at 21:54

3 Answers3

16

Just cast the integer to the enum:

SpiceLevels level = (SpiceLevels) 3;

and of course the other way around also works:

int number = (int) SpiceLevels.Ferocious;

See also MSDN:

Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int.

...

However, an explicit cast is necessary to convert from enum type to an integral type

Community
  • 1
  • 1
Julian
  • 33,915
  • 22
  • 119
  • 174
2
enum SpiceLevels { None = 0, Mild = 1, Moderate = 2, Ferocious = 3 };
static void Main(string[] args)
{
    int x = 3;
    Console.WriteLine((SpiceLevels)x);
    Console.ReadKey();
}
Julian
  • 33,915
  • 22
  • 119
  • 174
Krzysztof Wrona
  • 311
  • 5
  • 12
0

Enums inherit from Int32 by default so each item is assigned a numeric value, starting from zero (unless you specify the values yourself, as you have done).

Therefore, getting the enum is just a case of casting the int value to your enum...

int myValue = 3;
SpiceLevels level = (SpiceLevels)myValue;
WriteLine(level); // writes "Ferocious"
Roy G Davis
  • 336
  • 2
  • 5