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.
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:
1bool agrees;
2
3agrees = true;
4
5if (agrees)
6{
7 Console.WriteLine("The application may continue.");
8}
9else
10{
11 Console.WriteLine("Thank you for your interest, but we are unable to process your application at this time.");
12 Console.WriteLine("Have a nice day.");
13}
14
15// Add the following line to prevent the application from closing automatically
16Console.ReadLine();
When executed, the above code should produce the output shown in Fig. 1:
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.
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!
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.
1int temperature = 70;
2
3if (temperature < 65)
4{
5 Console.WriteLine("It is cold outside!");
6}
7else if (temperature >= 65 && temperature < 80)
8{
9 Console.WriteLine("It is a wonderful day!");
10}
11else
12{
13 Console.WriteLine("You'll need shorts and sandals!");
14}
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.
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 case
s 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.
1string job = "developer";
2
3switch(job)
4{
5 case "engineer":
6 Console.WriteLine("The engineer has been, and is, a maker of history.");
7 break;
8 case "developer":
9 Console.WriteLine("One of the best programming skills you can have is knowing when to walk away for awhile.");
10 break;
11 case "analyst":
12 Console.WriteLine("Leadership is solving problems.");
13 break;
14 default:
15 Console.WriteLine("I'm sorry. We could not find a quote for your job.");
16 break;
17}
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:
1string job = "developer";
2
3if (job == "engineer")
4{
5 Console.WriteLine("The engineer has been, and is, a maker of history.");
6}
7else if (job == "developer")
8{
9 Console.WriteLine("One of the best programming skills you can have is knowing when to walk away for awhile.");
10}
11else if (job == "analyst")
12{
13 Console.WriteLine("Leadership is solving problems.");
14}
15else
16{
17 Console.WriteLine("I'm sorry. We could not find a quote for your job.");
18}
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.
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.