C# provides many decision making statements that help the flow of the C# program based on certain logical conditions. C# includes the following decision making statements.
- if statement
- if-else statement
- switch statement
- Ternary operator:?
Here, you will learn about the if statements.
Syntex:
if(boolean expression) { // execute this code block if expression evalutes to true }
The if statement contains boolean expression inside brackets followed by a single or multi-line code block. At runtime, if a boolean expression is evaluates to true then the code block will be executed.
Consider the following example where the if condition contains true as an expression.
Example: if condition
if(true) { Console.WriteLine("This will be displayed."); } if(false) { Console.WriteLine("This will not be displayed."); }
As mentioned above, if statement can contain a boolean expression. An expression which returns either true or false. Following example uses the logical expression as a condition:
Example: if condition
int i = 10, j = 20; if (i > j) { Console.WriteLine("i is greater than j"); } if (i < j) { Console.WriteLine("i is less than j"); } if (i == j) { Console.WriteLine("i is equal to j"); }
if-else Statement
C# also provides for a second part to the if statement, that is else. The else statement must follow if or else if statement. Also, else statement can appear only one time in a if-else statement chain.
Example: if elseint i = 10, j = 20; if (i > j) { Console.WriteLine("i is greater than j"); } else { Console.WriteLine("i is either equal to or less than j"); }
else if Statement
The 'if' statement can also follow an 'else' statement, if you want to check for another condition in the else part.
Example: else if
static void Main(string[] args) { int i = 10, j = 20; if (i > j) { Console.WriteLine("i is greater than j"); } else if (i < j) { Console.WriteLine("i is less than j"); } else { Console.WriteLine("i is equal to j"); } }
Nested if Statements
C# alows nested if else statements. The nested 'if' statement makes the code more readable.
int i = 10; if (i > 0) { if (i <= 100) { Console.WriteLine("i is positive number less than 100"); } else { Console.WriteLine("i is positive number greater than 100"); } }
0 Comments