In this chapter, learn how to use the C# switch statement as a cleaner alternative to complicated if.. else if… statements.
In the previous chapter, we looked at controlling program execution flow using the if and else statements. While these statement constructs work well for testing a limited number of conditions, they quickly become unwieldy when dealing with larger numbers of possible conditions. C# has inherited the switch
statement from the C programming language.
In this chapter, we will explore the switch
statement in detail.
Why use the switch
statement?
For a small number of logical evaluations of a value, the if
… else if
… construct is perfectly adequate. Unfortunately, any more than two or three possible scenarios can quickly make such a construct both time-consuming to write and difficult to read. As a case in point, consider the following code example. The program uses if
… else if
… statements to identify the manufacturer of a car based on the model name:
string carModel = "Corolla";
string carManufacturer;
if ((String.Compare(carModel, "Patriot") == 0) ||
(String.Compare(carModel, "Liberty") == 0) ||
(String.Compare(carModel, "Wrangler") == 0)) {
carManufacturer = "Jeep";
}
else if (String.Compare(carModel, "Focus") == 0) {
carManufacturer = "Ford";
}
else if (String.Compare(carModel, "Corolla") == 0) {
carManufacturer = "Toyota";
} else {
carManufacturer = "unknown";
}
System.Console.Write($"Manufacturer is {carManufacturer}");
Code language: C# (cs)
As you can see, while the code is not too excessive, it is already starting to become somewhat hard to read and took more time to write than necessary. Imagine, however, if instead of 3 car models, we had to test for 10 or 20 models. Clearly, an easier solution is needed, and that solution is the switch
statement.
Using the switch
statement syntax
The syntax for a C# switch
statement is as follows:
switch (value)
{
case constant:
statements
break/jump
case constant:
statements
break/jump
default:
statements
break/jump
}
Code language: C# (cs)
This syntax needs a little explanation before we embark on creating a switch
based version of the above if
… else if
… construct.
In the above syntax outline, value represents either a value or an expression that returns a value. This is the value against which the switch
operates. Using our example, this would be the string representing the car model.
For each possible match, a case
statement is required, followed by a constant value (once again, using our example, this would be the car models). Each case constant must be of the same type as the governing value. Following from the case line are the C# statements that are to be executed if the value matches the case
constant.
After the statements comes an optional break
, goto
, or continue
statement. These statements are used either to break out of the switch statement when a match is found, jump a specific location in the code, or skip any remaining code in a loop and begin the next iteration.
Finally, the default:
section of the construct defines what should happen if none of the case
statements present a match to the value.
A switch
statement example
With the above information in mind, we may now construct a switch statement that provides the same functionality as our previous and somewhat unwieldy if
… else if
… construct:
string carModel = "Corolla";
string carManufacturer;
switch (carModel) {
case "Patriot":
case "Liberty":
case "Wrangler":
carManufacturer = "Jeep";
break;
case "Focus":
carManufacturer = "Ford";
break;
case "Corolla":
carManufacturer = "Toyota";
break;
default:
carManufacturer = "unknown";
break;
}
System.Console.Write($"Manufacturer is {carManufacturer}");
Code language: C# (cs)
Explaining the example
In the above example, the string assigned to the carModel
variable is used as the governing variable in the switch
statement. As is the case with the Jeep manufacturer, case
statements may be grouped together, preceding a single set of statements.
The default option simply sets the carManufacturer
string to “unknown” if none of the case
statements match the car model string.
Using goto
in a C# switch
statement
In the above example, we used break
to exit out of the switch
statement. The result of this is to move the point of program execution to the statements immediately following the switch
statement. Unfortunately, this presents a problem when the default
statements must be executed. To address this requirement, we can replace the break
statements in our example code with a goto default
statement:
string carModel = "Corolla";
string carManufacturer = "unknown";
switch (carModel) {
case "Patriot":
case "Liberty":
case "Wrangler":
carManufacturer = "Jeep";
goto default;
case "Focus":
carManufacturer = "Ford";
goto default;
case "Corolla":
carManufacturer = "Toyota";
goto default;
default:
System.Console.WriteLine ($"The {carModel} is manufactured by {carManufacturer}");
break;
}
Code language: C# (cs)
While the goto
statement could also be used to jump to a labeled location in our C# code; using it in this way is strongly discouraged. The abovementioned use is the only acceptable use of the goto statement in a modern object-oriented language such as C#. As any veteran programmer will tell you, if you find yourself in a position where a goto statement is your only way of achieving something, then you need to re-think and re-structure your code so that you no longer need the goto
.
Using continue
in a C# switch statement
Another alternative to the break
statement is the continue
statement. If the switch
statement is part of a loop, the continue
statement will cause execution to return immediately to the beginning of the loop, bypassing any subsequent code yet to be executed in the current loop iteration.
The use of the continue
statement in loops will be covered in the next lesson.