C# if else Statements

In this lesson, you will learn about if, else-if, and else conditions statements in C#, their usage, and examples to better understand the topic.


C# if, else if, else Statements

In C#, if, if-else, and else statements are decision-making statements that you can use to decide how your program should behave. It’s essential to understand how these statements work, as they are important, and you will see them everywhere in C# programs.

In this lesson, we will cover the following decision-making statements

  • if statement
  • else if statement
  • else statement

‘if’ statement in C#

The ‘if’ statement evaluates a condition; if it’s true, the code inside the if block (between the two brackets) is executed. Otherwise, the code will resume to the next command.


Syntax of if condition in C#

The following is the syntax of the ‘if’ condition in C#

if (condition) 
{
  // code to execute if the condition is true
}

Example of if condition in C#

The example below compares two variables, then prints the output based on the evaluation:

‘else if’ statement in C#

Another ‘if’ related condition in C# is the ‘else if’ condition. You can use the ‘else if’ statement to evaluate another expression if the first ‘if’ is false.


Syntax of ‘else if’ condition in C#

if (condition) {
  // code to execute if the condition is true
} else if {
  // code to execute if the second 'if' is true
}

Example of ‘else if’ condition in C#

In the example above, if the user enters the first number less than the second number, then the condition is false, and the cursor jumps to check the next condition, the ‘else if’. If true, the code block will be executed; else, the program will continue to the next statement.


‘else’ statement in C#

The ‘else’ statement will be executed if all the conditions are false.

Syntax of ‘else’ in C#

if (Condition1) // returns true
{
  // code block
} else if (Condition2) {
  // code block
} else {
  // executed if both Condition1 and Condition2 are false
}

Example of ‘else’ in C#

Nested if Statements

The Nested ‘if’ statements are two or more inside each other.

Example

This concludes the C# if else Statements lesson. In the next lesson, you will learn about the Switch Statement in C#.