In this tutorial, we will learn about the if... else... and if... else if... conditional statements and use them to add logic to our C# programs. The if... statements in C# will help us as we begin to write more advanced programs.
What is a Conditional?
A conditional statement in computer programming tells our program to do something based on the value of some condition. If a given condition evaluates to true, we might execute one block of code. If the condition is false, we might execute another block of code. Here are examples of some simple conditions you experience every day:
- if (hungry), then Eat;
- if (thirsty), then Drink;
- if (tired), then Sleep;
In the same way, we can use if
statements to tell our program to perform certain functions based on a variety of conditions. We can expand the statement to tell our program to run a certain block of code if the condition is true, but run a different block of code if the condition is false. We will do this by using an if-else
conditional statement.
C# if... Statement Example
Let's dive deeper by writing some code. In our example, we will create a simple game. Begin by creating a new Project (File > New > Project...). Be sure to select the C# .NET Core Console Application project template. You can call the project Decisions. Now, write the following inside your static void Main
code block:
Console.WriteLine("Win a Prize!");
Console.Write("Choose a door: 1, 2, or 3: ");
string userChoice = Console.ReadLine();
if (userChoice == "1")
{
string message = "You won a new computer!";
Console.WriteLine(message);
}
Console.ReadLine();
We could make a decision based on any number of conditions, but in this case, our program's decision will be made based on the value the user types in. We learned how to get user input with Console.ReadLine() in the previous tutorial, so we have saved that value into the userChoice variable on line 11.
On Line 13, we are making a comparison to see if whatever the user typed is equal to the literal string "1". If it is, then we will display a message saying the user has won a new computer. Notice, to make that comparison we are using the ( == ) Relational Operator. Recall, a single equals sign ( = ) is an Assignment Operator that assigns whatever value is on the right of the operator to the variable that is on the left. You can see this in Line 11. The double equals sign ( == ), on the other hand, is used to evaluate whether what is on the left is equal to what is on the right. The comparison will be TRUE if the two values are equal, or FALSE if they are not.
If the expression within the parentheses of our if
statement evaluates to true, then our program will execute the code inside the code block between lines 14 and 17. If the expression is not true, the statements inside the code block will be ignored and our program will continue with the statement on line 19.
C# if... else if... Example
If we run our code now, our program will do something if the user types "1," but nothing will happen if they type "2" or "3." We need to expand our example to compare the user's input against these other other possible strings.
Console.WriteLine("Win a Prize!");
Console.Write("Choose a door: 1, 2, or 3: ");
string userChoice = Console.ReadLine();
if (userChoice == "1")
{
string message = "You won a new computer!";
Console.WriteLine(message);
}
else if (userChoice == "2")
{
string message = "You won a new monitor!";
Console.WriteLine(message);
}
else if (userChoice == "3")
{
string message = "You won a new keyboard!";
Console.WriteLine(message);
}
Console.ReadLine();
When we have additional conditions to evaluate, we can use the else if
statement, as shown on Lines 18 and 23. If the evaluation in Line 13 is true, the additional checks will not run. If the condition is not true, our program will continue to Line 18 and evaluate that statement. Similarly, if the condition in Line 18 is true, the code block between Lines 19 and 22 will run and any future conditions in the if... else if... construct will not be evaluated; if the condition is false, it will skip the code block and evaluate the next condition (Line 23).
C# if... else if... else Example
Suppose the user enters "4" or a series of random letters instead of the numbers 1, 2, or 3. Right now, our code does not have a way to account for these scenarios. We need a catch-all case that will handle any conditions outside the ones we have explicitly tested for. To do this, we will add an else
statement at the end of our if... else if... construct.
Console.WriteLine("Win a Prize!");
Console.Write("Choose a door: 1, 2, or 3: ");
string userChoice = Console.ReadLine();
if (userChoice == "1")
{
string message = "You won a new computer!";
Console.WriteLine(message);
}
else if (userChoice == "2")
{
string message = "You won a new monitor!";
Console.WriteLine(message);
}
else if (userChoice == "3")
{
string message = "You won a new keyboard!";
Console.WriteLine(message);
}
else
{
string message = "You lose. Better luck next time.";
Console.WriteLine(message);
}
Console.ReadLine();
The else
statement in line 28 catches every other possible value of the userChoice variable, no matter what user types in. It is important when coding to make sure all possible scenarios are accounted for so our program delivers the expected results. In this case, the else
in our if... else if... else construct serves as that default catch-all for situations when the user enters a value outside the expected values.
Code Cleanup - A Complete if... else if... else... Example
You will notice a lot of redundancies in our if... else if... else code examples. For instance, we are executing Console.WriteLine(message);
in every single code block. Since we want to run this line no matter what, it would make more sense to place it after all our if statements.
Second, we have declared and assigned our message variable in each code block of our if statements. It would be better practice to declare the string variable once before testing all the conditions, and then simply assign a value to the variable depending on the user's input.
Finally, since we now have only one line of code beneath each if
statement, we can omit the curly braces to make our code even cleaner and easier to read.
using System;
namespace Decisions
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Win a Prize!");
Console.Write("Choose a door: 1, 2, or 3: ");
string userChoice = Console.ReadLine();
string message = "";
if (userChoice == "1")
message = "You won a new computer!";
else if (userChoice == "2")
message = "You won a new monitor!";
else if (userChoice == "3")
message = "You won a new keyboard!";
else
message = "You lose. Better luck next time.";
Console.WriteLine(message);
Console.ReadLine();
}
}
}
The Bottom Line
In this tutorial, we have seen examples of how to use if... else if... else... statements to add conditional logic to our programs. We have learned how these statements can help us when we want to run specific code blocks based on some condition. This construct will be very useful as we write more advanced C# programs. If you have any questions, let me know in the comments below!
Don't stop learning!
There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.
Did you know?
Our beautiful, multi-column C# reference guides contain more than 150 tips and examples to make it even easier to write better code.
Get your cheat sheets