Conditional statements in C#

3D Game Design with Unity

🕑 This lesson will take about 18 minutes

Conditional statements are used so that your program can make decisions. When your program has a range of conditions, you can build powerful algorithms. In this tutorial, you will learn about if statements, if/else statements, and if/else if statements. Watch the video below and then scroll down to see the sample code.

Is YouTube blocked at school? Watch on Google Drive.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10) {

print("Hello World");

}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

if/else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if/else statements allow you to specify what action will occur when a condition evaluates to true and also what will occur if the condition evaluates to false. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18) {  print("You are old enough to vote"); } else {  print("You are not old enough to vote"); }

if/else if statement

The limitation of the if/else statement is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the if/else if statement comes in.

The if/else if statement provides more options than the if/else statement. It is set up in the same way but it has more than one condition. The else part is optional in an if/else if statement.

Here is some sample code for the if/else if statement:

if(age>=18) {

print("You are old enough to vote");

} else if(age==17) {

print("You can vote after your next birthday");

}

else {

print("You are not old enough to vote");

}