Home

Defining Enumerated Switches in C#

|
Updated:  
2018-01-30 12:33:06
|
C# 2010 All-in-One For Dummies
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 author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Bill Sempf is a seasoned programmer and .NET evangelist specializing in .NET applications.

Chuck Sphar is a programmer and former senior technical writer for the Visual C++ product group at Microsoft.