We use enum
keyword for declaring enumeration with enumeration list and switch
enum can be used with switch
statement, the following example demonstrates that how to use enum
with switch
statement.
public enum Month { Jan, Feb, Mar, Apr } class Enum_With_Switch { static void Main() { Month temp_Month = Month.March; switch (temp_Month) { case Month.Jan: Console.WriteLine("this is January"); break; case Month.Feb: Console.WriteLine("this is February"); break; case Month.Mar: Console.WriteLine("this is March"); break; case Month.Apr: Console.WriteLine("this is April"); break; default: Console.WriteLine("Not the valid month"); break; } } }
One more thing about the enum
is that by default the first enumerator has the value 0, and the value of each successive enumerator is increased by 1 so we can also write the switch statement as in the below. The code will give the same output as above.
Month temp_Month = Month.March; switch (temp_Month) { case 0 Console.WriteLine("this is January"); break; case 1: Console.WriteLine("this is February"); break; case 2: Console.WriteLine("this is March"); break; case 3: Console.WriteLine("this is April"); break; }
Using if-else statements with above example
You know that the switch
statement is often used as an alternative to an if-else
statements. The above code can be written as follows using if-else
statements.
Month temp_Month = Month.March; if (temp_Month == Month.Jan) Console.WriteLine("this is January"); else if (temp_Month == Month.Feb) Console.WriteLine("this is February"); else if (temp_Month == Month.Mar) Console.WriteLine("this is March"); else if (temp_Month == Month.Apr) Console.WriteLine("this is April"); else Console.WriteLine("Not the valid month");