In the previous C# tutorial, we have learned about C# if statement . In this tutorial, we are going to learn about the C# if-else statement. If you have learned about the if statement then you know that the if contains code execution only when a boolean expression is true. In simple language, the code in the C# if the statement can be executed only if the expression is true if the boolean expression is false then no statement is executed. Therefore, the code in the C# if- else statement is executed even if the boolean expression is true, and another code is executed when the boolean expression is false.
Let's understand the if-else statement in C# programming.
C# If-else statement works for two states. If the boolean expression is true then execute the code of the if block and if the boolean expression is false then execute the else block .
The else block has been added to the if statement to allow the code to be set even if the expression is true and false.
if(boolean expression){ code to be executed if expression is true; } else { code to be executed if the expression is false; }
Let's create an example in C# programming.
using System;
namespace IfelseStatementProgram{
class IfelseStatement{
static void Main(string[] args) {
int x = 7;
int y=16;
if (x>y) {
/*if the expression is true, execute the if block */
Console.WriteLine("Boolean exp, True , 1");
Console.WriteLine("x is greater than y , x="+x+", y="+y);
}
else{
/*If the expression is false, execute the else block */
Console.WriteLine("y is greater than x , x="+x+", y="+y);
}
Console.ReadLine();
}
}
}
Output
y is greater than x , x=7, y=16
In the above C# if-else example, we declared and defined two variables. The value of a is 7 and the value of y is 16. We created an expression (condition ) x greater than y and else part. The compiler checks the expression but the expression is evaluated false after that compile execute the else block because of C# if the expression is evaluated to false.
Let's create another example of C# if-else statement.
using System;
namespace IfelseStatementProgram{
class IfelseStatement{
static void Main(string[] args) {
int x =17;
int y=10;
if (x>y) {
/*if the expression is true, execute the if block */
Console.WriteLine("Boolean exp, True , 1");
Console.WriteLine("x is greater than y , x="+x+", y="+y);
}
else{
/*if the expression is false, execute the else block */
Console.WriteLine("y is greater than x , x="+x+", y="+y);
}
Console.ReadLine();
}
}
}
Output
Boolean exp, True , 1 x is greater than y , x=17, y=10
In this C# example, if the expression evaluates to true, compiler executes the if block and never checks the else bock because of the if expression is evaluated to true. If the expression is evaluated to false, the compiler executes the else block.