Defining Enumerated Switches in C#

By John Paul Mueller, Bill Sempf, Chuck Sphar

When working with a switch statement in C#, the reason for a decision can be quite unclear if you use a numeric value. For example, the following code doesn’t really tell you much about the decision-making process:

// Create an ambiguous switch statement.

int mySelection = 2;

switch (mySelection)

{

case 0:

Console.WriteLine("You chose red.");

break;

case 1:

Console.WriteLine("You chose orange.");

break;

case 2:

Console.WriteLine("You chose yellow.");

break;

case 3:

Console.WriteLine("You chose green.");

break;

case 4:

Console.WriteLine("You chose blue.");

break;

case 5:

Console.WriteLine("You chose purple.");

break;

}

This code leaves you wondering why mySelection has a value of 2 assigned to it and what those output statements are all about. The code works, but the reasoning behind it is muddled. To make this code more readable, you can use an enumerated switch, like this:

// Create a readable switch statement.

Colors myColorSelection = Colors.Yellow;

switch (myColorSelection)

{

case Colors.Red:

Console.WriteLine("You chose red.");

break;

case Colors.Orange:

Console.WriteLine("You chose orange.");

break;

case Colors.Yellow:

Console.WriteLine("You chose yellow.");

break;

case Colors.Green:

Console.WriteLine("You chose green.");

break;

case Colors.Blue:

Console.WriteLine("You chose blue.");

break;

case Colors.Purple:

Console.WriteLine("You chose purple.");

break;

}

The output is the same in both cases: “You chose yellow.” However, in the second case, the code is infinitely more readable. Simply by looking at the code, you know that myColorSelection has a color value assigned to it. In addition, the use of a Colors member for each case statement makes the choice clear. You understand why the code takes a particular path.