If…Else Statements | C#
2 min readJan 27, 2022
- WHAT IT IS: If-Else statements allow you to create logic based on some conditions and they work very well with variables.
- NOTE: If statements can only run inside of methods.
- WHAT IS DOES: If-Else statements check a Boolean expression and execute the code based on if the expression is true or false.
A BREAKDOWN: The if part of the code executes when the value of the expression is true. The else part of the code is executed when the value of the expression is false
- Use
if
to specify a block of code to be executed, if a specified condition is true - Use
else
to specify a block of code to be executed, if the same condition is false - Use
else if
to specify a new condition to test, if the first condition is false - Use
switch
to specify many alternative blocks of code to be executed
EXECUTION:
Use the if
statement to specify a block of C# code to be executed if a condition is True
.
if (condition)
{
// block of code to be executed if the condition is True
}
Note that if
is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the below example, we are testing to see if 20 is greater than 18. If it is true, print some text:
if (20 > 18)
{
Console.WriteLine("20 is greater than 18");
}
Else Statement
Use the else
statement to specify a block of code to be executed if the condition is False
.
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
Execution:
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
// Outputs "Good evening."