Author avatar

Recnac

A Comprehensive Walkthrough of C# Conditional Statements Part 1 - if, else

Recnac

  • Jun 14, 2019
  • 10 Min read
  • 111 Views
  • Jun 14, 2019
  • 10 Min read
  • 111 Views
Programming Languages
C#

Introduction

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 question conditional 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.

  1. First, I will start with an interesting scenario.
  2. Then I will show you the code templates and flowcharts of all kinds of conditional statements.
  3. In addition, we will compare them and summarize the best practice.
  4. Finally, we will talk about advanced usages.

This guide (Part 1) will focus on the basic concept and introduce the most important conditional statement: if-else statement.

Getting Started

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.

1
2
3
4
5
6
7
8
9
10
11
string hamletChoice = "to be";
if (hamletChoice == "to be")
{
    // hamlet chose "to be"
    Console.WriteLine("suffer the slings and arrows of outrageous fortune");
}
else
{
    // otherwise, hamlet chose "not to be"
    Console.WriteLine("take arms against a sea of troubles, and by opposing end them");
}
csharp

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.

`if` Statement

Scenario

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.

Syntax

Before this, let me introduce the grammar of if in C#. This is the code template:

1
2
3
4
5
6
7
8
if (condition)
{
    if_block;
}
else
{
    else_block;
}
csharp

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.

Flowchart

I drew a flowchart of if-else statements to help you understand flow control better.

conditional statements flowchart - if else

We can figure out the process according to the flowchart:

  1. Check whether it satisfies condition.
  2. If condition is met, process the logic in if_block.
  3. If not, process the logic in else_block. else_block is optional because sometimes we do not care about else branch.

Practice

Single if Version

In 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
2
3
4
5
// get current time
DateTime now = DateTime.Now;
// if it is Saturday or Sunday
if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday)
    Console.WriteLine("Happy weekend! It's time to have fun!");
csharp
Discussion About Omitting Curly Braces

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 Version

In 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.

1
2
3
4
5
6
DateTime now = DateTime.Now;
// DateTime uses 24-hour time system, 17:00 is 5:00 pm
if (now.Hour < 17)
    Console.WriteLine("good day");          // before 17:00
else
    Console.WriteLine("good night");        // after 17:00
csharp

Combinations

Inclusive / Nested

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:

1
2
3
4
5
6
7
8
9
10
11
12
DateTime now = DateTime.Now;
string gender = 'female';
// DateTime uses 24-hour time system, 17:00 is 5:00 pm
// first check the hour
if (now.Hour > 17)
{
    // then check the gender
    if (gender == 'male')
        Console.WriteLine("good evening, sir");
    else
        Console.WriteLine("good evening, madam");
}
csharp

Parallel

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// nested if statements
DateTime now = DateTime.Now;
if (now.Hour < 12)                				// 0:00 - 12:00
{
    Console.WriteLine("good morning");
}
else                                        	// 12:00 - 24:00
{
    if (now.Hour < 17)
    {
    	Console.WriteLine("good afternoon");	// 12:00 - 17:00
    }
    else
    {
    	Console.WriteLine("good evening");		// 17:00 - 24:00    
    }
}
csharp

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
2
3
4
5
6
7
8
// parallel if statements
DateTime now = DateTime.Now;
if (now.Hour < 12)
    Console.WriteLine("good morning");		// 0:00 - 12:00
else if (now.Hour < 17)
    Console.WriteLine("good afternoon");    // 12:00 - 17:00
else
    Console.WriteLine("good evening");      // 17:00 - 24:00
csharp

Alternatively, we can use a switch statement in such a condition, which will be introduced in the next guide.

Conclusion

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.

conditional statements mind map

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]

0