13

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?

1
  • 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. Commented Jan 15, 2017 at 21:54

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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();
}

Comments

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.