A Comprehensive Walkthrough of C# Conditional Statements Part 2 - switch
In this guide, we will focus on the important conditional switch statement, then summarize the best practices for conditional choice.
Jun 14, 2019 • 10 Minute Read
Introduction
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.
- First, I will start with an interesting scenario.
- Then I will show you the code templates and flowcharts of all kinds of conditional statements.
- In addition, we will compare them and summarize the best practice.
- Finally, we will talk about advanced usages.
switch Statements
Scenario
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.
Syntax
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.
switch (expression)
{
case value1:
code_block1;
break;
case value2:
case value3:
code_block2;
break;
...
default:
code_blockN;
break;
}
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.
Flowchart
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:
- Use the case value to match expression.
- If one value matches, check whether it has code_block:
- If it does, execute it and exit.
- If not, fall through until it finds a code_block.
- If there are no value matches, choose the default branch. If default doesn't exist, exit directly.
Practice
Since we have learned the mechanism of switch, it is time to solve an example problem:
string trafficLight = "Yellow";
// split logic based on trafficLight
switch (trafficLight)
{
case "Green":
Console.WriteLine("pass smoothly");
break;
case "Yellow": // fall through to "Red" branch
case "Red":
Console.WriteLine("slow down and stop");
break;
default: // rest conditions
Console.WriteLine("recognize failed, notify driver to decide");
break;
}
Advanced Features
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.
Best Practice for Conditional Choice
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:
- The first thing taken into consideration is branch number.
- If there is only one branch, we choose if. If two, choose if-else.
- If there are more than two branches, we further consider: do all conditions match a single expression?
- If yes, make a decision dependent on the complexity of the logic. If simple, use switch. Otherwise, use parallel if-else.
- If no, we should analyze the logic relationship. If inclusive, use nested if-else. Otherwise, use parallel if-else.
Advanced Usages
Cooperate with Iterative Statement
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.
Random random = new Random();
int target = random.Next(1, 21); // generate a random number 1-20
Console.WriteLine("please guess a number between 1 and 20.");
int current;
// use do-while to let user guess repetitively
do
{
current = int.Parse(Console.ReadLine());
// use parallel if-else to split logic into branches
if (current > target)
Console.WriteLine("your guess {0} is greater, keep trying!", current);
else if (current < target)
Console.WriteLine("your guess {0} is smaller, keep trying!", current);
else
Console.WriteLine("bingo! the target number is {0}!", target);
} while (current != target);
Let's play this game:
please guess a number between 1 and 20.
>> 12
your guess 12 is greater, keep trying!
>> 7
your guess 7 is smaller, keep trying!
>> 9
bingo! the target number is 9!
Cooperate with Jump Statement
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.
Conclusion
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:
- A Comprehensive Walkthrough of C# Iterative Statements Part 1 - while, do
- A Comprehensive Walkthrough of C# Iterative Statements Part 2 - for, foreach
- A Comprehensive Walkthrough of C# Iterative Statements Part 3 - advanced usages
- A Comprehensive Walkthrough of C# Conditional Statements Part 1 - if, else
- A Comprehensive Walkthrough of C# Conditional Statements Part 2 - switch
- A Comprehensive Walkthrough of C# Jump Statements Part 1 - break, continue
- A Comprehensive Walkthrough of C# Jump Statements Part 2 - goto
Hope you enjoyed it. If you have any questions, you’re welcome to contact me at recnac@foxmail.com.