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.
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
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.
The following is the syntax of the ‘if’ condition in C#
if (condition) { // code to execute if the condition is true }
The example below compares two variables, then prints the output based on the evaluation:
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.
if (condition) { // code to execute if the condition is true } else if { // code to execute if the second 'if' is true }
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.
The ‘else’ statement will be executed if all the conditions are false.
if (Condition1) // returns true { // code block } else if (Condition2) { // code block } else { // executed if both Condition1 and Condition2 are false }
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#.