When you start to learn a programming language such as C#, one of the most important concepts is Flow Control. We know a program is composed of statements. The way that we combine these statements is what makes a program more powerful. And this is the responsibility of flow control: control the flow of program execution.
Sequential execution, one by one, is not enough for many situations. So, flow control provides many useful statements such as conditional statements, iterative statements, jump statements, and other advanced features. In this guide, we will focus on an important flow control in C#: Conditional Statements.
A Conditional Statement is widely used, even used in Shakespeare's famous quote:
To be, or not to be, that is the
questionconditional statement.
That is a joke, but we are really going to learn how to code this quote in this guide.
As this is a guide for beginners, I will try my best to use vivid visualizations and examples to help you understand.
This guide (Part 1) will focus on the basic concept and introduce the most important conditional statement: if-else
statement.
Some readers might be curious: What is a conditional statement? And why do we need it?
Let's go back to the quote "to be, or not to be.”
We could notice the logic is split into two branches: the result of choosing "to be" and the result of choosing "not to be." Sequential execution is unable to complete this task. So we need conditional statements to help us.
1string hamletChoice = "to be";
2if (hamletChoice == "to be")
3{
4 // hamlet chose "to be"
5 Console.WriteLine("suffer the slings and arrows of outrageous fortune");
6}
7else
8{
9 // otherwise, hamlet chose "not to be"
10 Console.WriteLine("take arms against a sea of troubles, and by opposing end them");
11}
Actually, this code is very intuitive and self-explanatory, right?
If the condition is true, it will execute if
block. If not, it will execute else
block.
This is the most basic conditional statement to solve the problem when your program needs logic branches.
Imagine this scenario:
We are going to develop a simple greeting machine. It will greet on some specific time, such as "good morning" or "happy weekend".
The if
statement is suitable in this situation.
Before this, let me introduce the grammar of if
in C#. This is the code template:
1if (condition)
2{
3 if_block;
4}
5else
6{
7 else_block;
8}
The if
statement is composed of condition
, if_block
, and else_block
.
condition
is a boolean expression. It decides to execute if_block
or else_block
.if_block
represents the logic if condition
is true. It can include multiple statements, even another if
block.else_block
represents the logic if condition
is false. It is optional. Remove else
branch when there is no logic in else
.I drew a flowchart of if-else
statements to help you understand flow control better.
We can figure out the process according to the flowchart:
condition
.condition
is met, process the logic in if_block
.else_block
. else_block
is optional because sometimes we do not care about else
branch.if
VersionIn the first version, the greeting machine says, "Happy weekend! It's time to have fun!" when it is Saturday or Sunday.
Let's start with the first version. Obviously, we only need if
branch:
1// get current time
2DateTime now = DateTime.Now;
3// if it is Saturday or Sunday
4if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday)
5 Console.WriteLine("Happy weekend! It's time to have fun!");
As the above example shows, we can omit curly braces {}
if there is only a single statement in the block.
But is that a best practice?
There are different opinions about that. As for the discussion about Omit curly braces or not? here, omitting curly braces makes code concise and seems more readable, but sometimes may bring potential bugs when refactoring code according to Why is it considered a bad practice to omit curly braces?.
I refer to this advice, and it may be useful for your decision.
Each developer/team with his/her/their own conventions but Stylecop default rule is enabled to warn you for such violation.
Bottom line, you should use the convention that you like most and that is working for you, practices are nothing but guidance not set in stone.
if-else
VersionIn the second version, it says "good day" when the time is before 5:00 pm. Otherwise, it says "good night".
For this new version, we need else
to take care of the rest of the situation.
1DateTime now = DateTime.Now;
2// DateTime uses 24-hour time system, 17:00 is 5:00 pm
3if (now.Hour < 17)
4 Console.WriteLine("good day"); // before 17:00
5else
6 Console.WriteLine("good night"); // after 17:00
In the third version, it says "good evening" when the time is after 5:00 pm, and appends the "sir" or "madam" suffix according to the gender.
We can see there are two if
statements in this requirement. The relationship between them is inclusive and, as I have explained, if_block
can include another if
statement. So, we combine them in a nested way:
1DateTime now = DateTime.Now;
2string gender = 'female';
3// DateTime uses 24-hour time system, 17:00 is 5:00 pm
4// first check the hour
5if (now.Hour > 17)
6{
7 // then check the gender
8 if (gender == 'male')
9 Console.WriteLine("good evening, sir");
10 else
11 Console.WriteLine("good evening, madam");
12}
In the last version, it says "good morning" when the time is before 12:00 am, "good afternoon" when the time is between 12:00 am and 5:00 pm, and "good evening" the rest of the times.
Although it is inappropriate to allocate 0:00 am - 12:00 am to morning.
We can achieve this by using the nested technique. Split by "morning" first, then split by "afternoon" in else
.
1// nested if statements
2DateTime now = DateTime.Now;
3if (now.Hour < 12) // 0:00 - 12:00
4{
5 Console.WriteLine("good morning");
6}
7else // 12:00 - 24:00
8{
9 if (now.Hour < 17)
10 {
11 Console.WriteLine("good afternoon"); // 12:00 - 17:00
12 }
13 else
14 {
15 Console.WriteLine("good evening"); // 17:00 - 24:00
16 }
17}
But the nested version seems complicated and lacks ease of readability. To avoid it, we combine if
statements parallel, and use else if {..}
instead of else{ if {..} }
.
1// parallel if statements
2DateTime now = DateTime.Now;
3if (now.Hour < 12)
4 Console.WriteLine("good morning"); // 0:00 - 12:00
5else if (now.Hour < 17)
6 Console.WriteLine("good afternoon"); // 12:00 - 17:00
7else
8 Console.WriteLine("good evening"); // 17:00 - 24:00
Alternatively, we can use a switch
statement in such a condition, which will be introduced in the next guide.
In this guide, we have learned an important flow control in C#: Conditional Statement. It helps to process logic separately. We started with the basic concept of a conditional statement. Then we learned the most important conditional statement: if-else
statement. We analyzed the syntax and flowchart of if-else
and practiced them with examples. Furthermore, we talked about the combinations of if
statements: in nested and parallel ways.
In the second part, we will cover another important conditional statement: switch
statement. Then, we will compare them and summarized the best practice. In addition, we will explore advanced usages.
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].