Skip to main content

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 condition is true: the if body runs, and the else body is skipped
  • If condition is false: the else body runs, and the if body 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 condition1 is true: the if body runs, and the rest is skipped
  • Else, if condition2 is true: that body runs, and the rest is skipped
  • If neither is true: the else body 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");
}