In C# if-else is a common selection statement. An if-else statement checks the Boolean expression and executes the code based upon if the expression is true or false. An if part of the code will executes when the value of the expression is true. The else part of the code will executed when the value of the expression is false. The else portion of the if-else statement is optional.
Syntax of the if-else statement.
1. if (Boolean condition)
2. {
3. //code if condition is true
4. }
5. else
6. {
7. Statement
8. }
If statement
An if part of the statement or statement block is executed when the condition is true; if it is false, then the control executes the code in the else statement or else statement block.
The following example uses the if statement to check if the value of variable a is less than 0, then display a message, ‘a is negative’.
1. int a = -1;
2. if (a < 0)
3. {
4. Console.WriteLine("a is negative.");
5. }
If-else statement
As mentioned above, an if statement executes with one or more else statements. If the “if” condition will not true, then the program control goes to the “else” condition. In C# if-else statement also tests the condition. It will executes the if block if condition is true otherwise else block will be executed.
C# If-else Example
1. using System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. int num = 11;
7. if (num % 2 == 0)
8. {
9. Console.WriteLine("It is even number");
10. }
11. else
12. {
13. Console.WriteLine("It is odd number");
14. }
15.
16. }
17. }
Output:
It is odd number
Liked By
Write Answer
What is if-else statement in C#?
Join MindStick Community
You have need login or register for voting of answers or question.
Nishi Tiwari
21-Jan-2020In C# if-else is a common selection statement. An if-else statement checks the Boolean expression and executes the code based upon if the expression is true or false. An if part of the code will executes when the value of the expression is true. The else part of the code will executed when the value of the expression is false. The else portion of the if-else statement is optional.
Syntax of the if-else statement.
If statement
An if part of the statement or statement block is executed when the condition is true; if it is false, then the control executes the code in the else statement or else statement block.
The following example uses the if statement to check if the value of variable a is less than 0, then display a message, ‘a is negative’.
If-else statement
As mentioned above, an if statement executes with one or more else statements. If the “if” condition will not true, then the program control goes to the “else” condition. In C# if-else statement also tests the condition. It will executes the if block if condition is true otherwise else block will be executed.
C# If-else Example
Output: