Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Can you call an Enum by the number value? [duplicate]

Tags:

c#

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?

like image 264
MarsBars9459 Avatar asked Jan 15 '17 21:01

MarsBars9459


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is C full form?

History: The name C is derived from an earlier programming language called BCPL (Basic Combined Programming Language). BCPL had another language based on it called B: the first letter in BCPL.


2 Answers

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

like image 140
Julian Avatar answered Oct 11 '22 16:10

Julian


enum SpiceLevels { None = 0, Mild = 1, Moderate = 2, Ferocious = 3 };
static void Main(string[] args)
{
    int x = 3;
    Console.WriteLine((SpiceLevels)x);
    Console.ReadKey();
}
like image 30
Krzysztof Wrona Avatar answered Oct 11 '22 17:10

Krzysztof Wrona