This is the second part of a two-part series on C# Conditional Statements. In the first part, We delved into the if-else
statement and its combinations. Check it out in case you missed it.
In this guide, we will focus on another important conditional statement: switch
statement. Then we will compare them and summarize the best practice for conditional choice. Furthermore, we will learn the advanced usages.
As this is a guide for beginners, I will try my best to use vivid visualizations and examples to help you understand.
Imagine this scenario:
Implement a feature for an automatic drive system. Deal with the reactions when the automobile meets a traffic light.
If the traffic light is green, pass smoothly. If red, slow down and stop.
If yellow, refer to red light for a good driving habit. (Routes are countless. Safety is foremost.)
A switch statement is the best solution to this problem.
A switch
statement is often used as an alternative to if-else
if a single expression is tested against three or more conditions.
By convention, we’ll learn the syntax of the switch
statement first.
1switch (expression)
2{
3 case value1:
4 code_block1;
5 break;
6 case value2:
7 case value3:
8 code_block2;
9 break;
10 ...
11 default:
12 code_blockN;
13 break;
14}
The switch
statement allows expression
to control the flow of the program execution via a multi-way branch. Usually, it contains a group of case
branches and a default
branch:
expression
is the door leading to all branches. Before C# 7.0, it must be one of char
, string
, bool
, int
-like, and enum
. Afterward, expression
can be any non-null expression.value
is a candidate of expression
. If it matches expression
, this branch is chosen.code_block
represents the current branch logic. If it is empty, it will fall through the next branch. If not, it must be followed by a jump statement, such as break
. We will learn jump statements in another guide.default
is the default logic branch when none of case
value matches expression
. It can be omitted if you ensure case
covers all the solution spaces or if you don't care about the rest of the situations.Please take a look at the switch
flowchart. It shows flow control intuitively.
Through the above flowchart, we can figure out the execution process of switch
:
value
to match expression
.value
matches, check whether it has code_block
:code_block
.value
matches, choose the default
branch. If default
doesn't exist, exit directly.Since we have learned the mechanism of switch
, it is time to solve an example problem:
1string trafficLight = "Yellow";
2// split logic based on trafficLight
3switch (trafficLight)
4{
5 case "Green":
6 Console.WriteLine("pass smoothly");
7 break;
8 case "Yellow": // fall through to "Red" branch
9 case "Red":
10 Console.WriteLine("slow down and stop");
11 break;
12 default: // rest conditions
13 Console.WriteLine("recognize failed, notify driver to decide");
14 break;
15}
We have learned the essential features of switch
. This should be enough for most cases of your work.
But there are still some advanced features, such as type pattern in pattern matching (we use constant pattern) or using the when
clause in case
. You can refer to the official documentation if you are interested in learning more.
switch
vs. Parallel if-else
Both switch
and parallel if-else
create multiple branches.
Parallel if-else
is more powerful because the condition can be different and complicated in every branch. In contrast, switch
is more straightforward and readable.
So for the multiple branches situation, we give priority to switch
. If switch
is unable to accomplish this task, we use parallel if-else
alternatively.
Besides, another factor to consider is the complexity of code_block
. Although switch
is able to hold logic as complex as if-else
, simple logic is preferred. For the complex logic, we tend to use if-else
, or encapsulate into a method.
Now we have learned about if
and switch
statement, including their variations.
We are going to summarize the best practice to choose in particular scenario:
We can figure out the process to make the decision:
if
. If two, choose if-else
.switch
. Otherwise, use parallel if-else
.if-else
. Otherwise, use parallel if-else
.We have learned about iterative statements in the previous guide. The combination of conditional and iterative statement is a common technique.
Let's practice in the following scenario:
Design a guess number game. Generate a number rang ingfrom 1 to 20 and let the user guess. You should give a hint of whether the current guess is greater or smaller.
1Random random = new Random();
2int target = random.Next(1, 21); // generate a random number 1-20
3Console.WriteLine("please guess a number between 1 and 20.");
4int current;
5// use do-while to let user guess repetitively
6do
7{
8 current = int.Parse(Console.ReadLine());
9 // use parallel if-else to split logic into branches
10 if (current > target)
11 Console.WriteLine("your guess {0} is greater, keep trying!", current);
12 else if (current < target)
13 Console.WriteLine("your guess {0} is smaller, keep trying!", current);
14 else
15 Console.WriteLine("bingo! the target number is {0}!", target);
16} while (current != target);
Let's play this game:
1please guess a number between 1 and 20.
2>> 12
3your guess 12 is greater, keep trying!
4>> 7
5your guess 7 is smaller, keep trying!
6>> 9
7bingo! the target number is 9!
In the switch
section, we mentioned that a non-empty case should end with a jump statement such as break
or goto
.
On the other hand, most jump statements need the help of conditional statements because they only want to jump in some situations.
Because we need the prerequisite of a jump statement, we will discuss this combination in next guide: A Comprehensive Walkthrough of C# Jump Statements Part 1 - break, continue.
In this guide, we have learned the other conditional statement: switch
statement. We analyzed the syntax and flowchart of switch
and practiced with examples. Furthermore, we compared them and summarized the best practices. In the end, we talked about the advanced usages: how to cooperate with iterative and jump statement.
As this is the end, I have drawn a mind map to help you organize and review the knowledge in this series.
This guide is one of a series of C# Flow Control guides:
Hope you enjoyed it. If you have any questions, you’re welcome to contact me at [email protected].