Author avatar

Gabriel Cánepa

Using Conditional Statements Like If and Switch in C#

Gabriel Cánepa

  • Apr 2, 2019
  • 8 Min read
  • 2,642 Views
  • Apr 2, 2019
  • 8 Min read
  • 2,642 Views
Hosted
C#

Introduction

The concept of a computer program as a set of instructions that are executed one by one in order is familiar to anyone starting to code. This definition, although useful for introductory purposes, does not consider the frequent need for decision making. If we keep in mind that any useful software will invariably need to do this, we will have a better understanding of what a computer program is today.

To illustrate how to execute different portions of code based on a variety of conditions, in this guide we will use the if / else and switch / case statements in C# to write a simple console application.

If you want to follow along, you can use either Visual Studio Community or a professional edition, which we will assume is already installed on your local machine before we begin. Alternatively, an online C# compiler such as .NET Fiddle can come in handy if you are on a mobile device.

For simplicity, variables have hardcoded values in the following examples. However, in a real-world application, they are set as the end user interacts with the program by clicking on checkboxes, or entering text in a box, to name two examples.

Introducing if / else Constructs

Picture the following scenario. You need to determine the eligibility of a job applicant based on his or her acceptance of your company's terms and policies. If the person answers yes, the hiring process may continue. Otherwise, a polite message stating that the application cannot be processed is shown.

To address this, type the following code inside the Main() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool agrees;

agrees = true;

if (agrees)
{
	Console.WriteLine("The application may continue.");
}
else
{
	Console.WriteLine("Thank you for your interest, but we are unable to process your application at this time.");
	Console.WriteLine("Have a nice day.");
}

// Add the following line to prevent the application from closing automatically
Console.ReadLine();
csharp

When executed, the above code should produce the output shown in Fig. 1:

Figure 1 - A program with a simple if/else construct

Let us examine in detail what the program is doing:

  • A boolean variable called agrees is declared and later assigned the value true. Of course, you can alternatively perform both steps in the same line as bool agrees = true, depending on a matter of personal preference.

  • An if statement is accompanied by a condition check inside parentheses. Since we are dealing with a boolean variable, if (agrees) is the same as if (agrees == true) where the first alternative is preferred for brevity. This is then followed by a set of curly braces, which contains the code to be executed when the condition evaluates to true (displaying a short message with the text The application may continue).

  • When the condition evaluates to false, the code that follows the else clause will execute.

  • Outside the if / else we can write code that will run regardless of the above condition check. In this case, Console.ReadLine(); keeps the console window from closing automatically until we press Enter.

Now, let us consider another scenario. Let us suppose we are using our code to test temperature ranges and perform the following actions:

  • If temperature is below 65 °F, print It is cold outside! on the screen.

  • When temperature is greater or equal than 65 °F and less than 80 °F, we will say It is a wonderful day!

  • Otherwise, we want to display the message You'll need shorts and sandals!

We will follow essentially the same structure as before, only adding an else if clause after the if block. Fig. 2 shows the output of the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int temperature = 70;

if (temperature < 65)
{
	Console.WriteLine("It is cold outside!");
}
else if (temperature >= 65 && temperature < 80)
{
	Console.WriteLine("It is a wonderful day!");
}
else
{
	Console.WriteLine("You'll need shorts and sandals!");
}
csharp

Figure 2 - The else if statement

Besides the else if block, the above code also introduces the && (AND) logical operator. This causes the condition to be true when both expressions are.

To summarize, use an if block to enclose code that should be executed if a condition is met. Optionally, add a pair of curly braces following the else keyword to wrap code that will be run otherwise. Additionally, use else if in case that you need to try another alternative. In any event, keep in mind that we are ultimately testing for conditions that can be either true or false. Such conditions may come in the form of a single boolean variable or a more complex expression involving relational or logical operators.

Testing Multiple Conditions with Switch and Case

Although you can use as many else if blocks as you wish, two or more can easily cause the code to become difficult to read. That is where the switch / case structure enters the picture.

To begin, we will type the switch statement followed by the variable being tested inside parentheses as you can see in Fig. 3. Next, a series of cases control the execution flow based on the value of that variable. Each case ends with the break keyword, which tells the program to exit the switch block. Optionally, you can add a default clause to indicate which code should be run when none of the previous cases apply.

Figure 3 - The switch-case block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string job = "developer";

switch(job)
{
	case "engineer":
		Console.WriteLine("The engineer has been, and is, a maker of history.");
		break;
	case "developer":
		Console.WriteLine("One of the best programming skills you can have is knowing when to walk away for awhile.");
		break;
	case "analyst":
		Console.WriteLine("Leadership is solving problems.");
		break;
	default:
		Console.WriteLine("I'm sorry. We could not find a quote for your job.");
		break;
}
csharp

We can potentially implement the same solution as above with the following code, but you will note that it is not as easy to read - let alone if there were more alternatives to check:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string job = "developer";

if (job == "engineer")
{
	Console.WriteLine("The engineer has been, and is, a maker of history.");
}
else if (job == "developer")
{
	Console.WriteLine("One of the best programming skills you can have is knowing when to walk away for awhile.");
}
else if (job == "analyst")
{
	Console.WriteLine("Leadership is solving problems.");
}
else
{
	Console.WriteLine("I'm sorry. We could not find a quote for your job.");
}
csharp

So, if the result is the same, the question inevitably arises. When should we use a regular if / else if / else construct or a switch / case? The rule of thumb is: don't go with the former if you need more than one else if block. You will thank yourself later, and so will other developers reading and maintaining your code.

Summary

As you can see, you can learn programming concepts using familiar things and processes, and then easily apply that knowledge to a wide variety of scenarios and more importantly, to your specific needs. Additionally, you can always consult the if-else and switch-case reference in the Microsoft documentation site.

5