Course Content
C# Beyond Basics
C# Beyond Basics
Enumerators
Enum, also known as Enumerator, is a structure for grouping together some integral constants. The constants are basically of the type int
.
Following is the syntax for creating an enum:
index
enum EnumName { Const1, Const2, Const3, ... }
By default the first element of an enum has the value 0, the second element has a value 1
and so on.
For-example:
index
enum Days { Monday, // 0 Tuesday, // 1 Wednesday, // 2 Thursday, // 3 Friday, // 4 Saturday, // 5 Sunday // 6 }
We can access the values of these constants using the enumName.constantName
syntax.
For-example:
index
using System; enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } class ConsoleApp { static void Main(string[] args) { // Explicitly converting the enum elements to 'int' and then outputting them Console.WriteLine((int)Days.Monday); // 0 Console.WriteLine((int)Days.Wednesday); // 2 Console.WriteLine((int)Days.Friday); // 4 Console.WriteLine((int)Days.Sunday); // 6 } }
Note that in the above example we explicitly need to convert the constant into an int
datatype since these constants are of type Days
by default, which means that the enum Days
is a new datatype which we created. Therefore, it can be stored into a variable of type Days
:
This is useful in places like switch statements.
For-example:
index
using System; enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } class ConsoleApp { static void Main(string[] args) { Days day = Days.Friday; switch (day) { case Days.Monday: Console.WriteLine("It is Monday"); break; case Days.Tuesday: Console.WriteLine("It is Tuesday"); break; case Days.Wednesday: Console.WriteLine("It is Wednesday"); break; case Days.Thursday: Console.WriteLine("It is Thursday"); break; case Days.Friday: Console.WriteLine("It is Friday"); break; case Days.Saturday: Console.WriteLine("It is Saturday"); break; case Days.Sunday: Console.WriteLine("It is Sunday"); break; default: Console.WriteLine("Invalid Day"); break; } } }
We can also manually assign values to the enum constants. The unassigned constants take up incremented values of the previous elements:
index
using System; enum Days { Monday, Tuesday, Wednesday = 5, Thursday, Friday, Saturday = 10, Sunday } class ConsoleApp { static void Main(string[] args) { // Explicitly converting the enum elements to 'int' and then outputting them Console.WriteLine((int)Days.Monday); Console.WriteLine((int)Days.Tuesday); Console.WriteLine((int)Days.Wednesday); Console.WriteLine((int)Days.Thursday); Console.WriteLine((int)Days.Friday); Console.WriteLine((int)Days.Saturday); Console.WriteLine((int)Days.Sunday); } }
Thanks for your feedback!