Chaining Conditions
Sometimes a decision is more complex than a single yes/no question. C# gives us extra syntax for these cases.
if-else Statements
An if statement can have an optional else clause, which runs when the if condition is false.
if (condition)
{
// runs if condition is true
}
else
{
// runs if condition is false
}
// code after if
- If
conditionistrue: theifbody runs, and theelsebody is skipped - If
conditionisfalse: theelsebody runs, and theifbody is skipped
Example: Jacket
I should wear a jacket IF its cold OR it's raining, OTHERWISE i bring sunglasses.
double temp = 10;
bool isRaining = true;
if (temp < 5.0 || isRaining)
{
Console.WriteLine("🧥");
}
else
{
Console.WriteLine("🕶️");
}
else-if Statements
else if lets you chain multiple conditions together, checking them in order until one is true.
if (condition1)
{
// runs if condition1 is true
}
else if (condition2)
{
// runs if condition1 is false and condition2 is true
}
else
{
// runs if none of the above conditions are true
}
// code after if
- If
condition1istrue: theifbody runs, and the rest is skipped - Else, if
condition2istrue: that body runs, and the rest is skipped - If neither is
true: theelsebody runs
Example: Driving
I can drive a car IF i have a license AND I am above the legal driving age, OTHERWISE IF i am old enough, i need to hit the books OTHERWISE I must wait until i've come of age.
bool hasLicense = true;
int age = 20;
if (age >= 16 && hasLicense)
{
Console.WriteLine("🚗 toot toot");
}
else if (age >= 16)
{
Console.WriteLine("📚 grind time");
}
else
{
Console.WriteLine("no chance");
}