If else Statement
C# if else Statement we presented last time is only good if you want to execute a code when one condition is met. But what would you do if you want execute another set of codes when that condition is not met? The if else statement serves this purpose because it is a double selection conditional statement. It means you can specify another behavior when the specified condition is false. Below is the syntax of an if else statement.
if (condition)
{
code to execute if condition is true;
}
else
{
code to execute if condition is false;
}
The else keyword can’t be used by itself. It must have a matching if statement. The curly braces are optional if you only have one statement to execute for each of the body of if and else. The code inside the else block will only be executed if the condition inside the if statement results to false. I’ll show you an example of using the if else statement.
using System;
namespace IfElseStatementDemo
{
public class Program
{
public static void Main()
{
int number = 5;
//Test the condition
if (number < 10)
{
Console.WriteLine("The number is less than 10.");
}
else
{
Console.WriteLine("The number is either greater than or equal to 10.");
}
//Modify value of number
number = 15;
//Repeat the test to yield a different result
if (number < 10)
{
Console.WriteLine("The number is less than 10.");
}
else
{
Console.WriteLine("The number is either greater than or equal to 10.");
}
}
}
}
Example 1 – Using the if else Statement
The number is less than 10. The number is either greater than or equal to 10.
The output shows the functionality of the if else statement. When the value of number is less than 10, it met the condition and executes the code that is inside the if block. When the value of number was modified to have a value which is greater than 10, the condition resulted to false and the code block of else was executed. Do not use the else block if it has no corresponding if block. Like the if statement, do not add a semicolon immediately after the else keyword.