C-SHARP - 3.14 Enum
In this video we introduce enumerations in C#. An enum is a structure that groups several named constants together to make code easier to read. Suppose we want to represent the days of the week: declaring seven separate const int values quickly becomes verbose. An enumeration solves this in a single, compact declaration. By default the first constant equals 0 and the underlying type is int, but you can specify another integral type such as short or byte if needed.
To create an enumeration, we type enum outside the Main method but inside the Program class, give it a name (for example JoursSemaine) and list the constants between braces. We can force a starting value by assigning the first constant explicitly, and every following constant is incremented automatically. It is also possible to give the same value to several constants, which is useful for grouping things such as error levels of equal severity.
enum JoursSemaine
{
Lundi = 1,
Mardi,
Mercredi,
Jeudi,
Vendredi,
Samedi,
Dimanche
}
Using the enum
- Declare a variable:
JoursSemaine jour = JoursSemaine.Lundi;. - Display the name with
Console.WriteLine(jour);which printsLundi. - Cast to its underlying value with
(int)jour; forSamediwe obtain6.
Inside the Main method, declare a variable of type JoursSemaine, assign it one of the constants of the enumeration and display it. Running the program prints the constant name. To obtain its numeric value you add (int) in front of the variable inside the Console.WriteLine call. We will explore enumerations more deeply in later chapters; the next short video proposes an exercise to practise this new concept.