C# 7.0 All-in-One For Dummies
Book image
Explore Book Buy On Amazon
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.

About This Article

This article is from the book:

About the book authors:

John Paul Mueller is a writer on programming topics like AWS, Python, Java, HTML, CSS, and JavaScript. William Sempf is a programmer and .NET evangelist. Chuck Sphar was a full-time senior technical writer for the Visual C++ product group at Microsoft.

This article can be found in the category: