Lesson 18 +10 XP

If...Else

If...Else

C# uses if, else if, and else to run different code based on conditions.

The if statement

Use if to run code only when a condition is true:

if (20 > 18)
{
  Console.WriteLine("20 is greater than 18");
}

The else statement

else runs when the if condition is false:

int time = 20;
if (time < 18)
{
  Console.WriteLine("Good day.");
}
else
{
  Console.WriteLine("Good evening.");
}

The else if statement

else if adds another condition to check:

int time = 22;
if (time < 10)
{
  Console.WriteLine("Good morning.");
}
else if (time < 20)
{
  Console.WriteLine("Good day.");
}
else
{
  Console.WriteLine("Good evening.");
}

Short hand if...else (ternary)

For simple two-way decisions, use the ternary operator ? ::

int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
Console.WriteLine(result);

If the condition is true, the left value is used; otherwise the right value.

TL;DR

  • if runs code when the condition is true.
  • else handles everything else.
  • else if checks another condition.
  • The ternary ? : is a short hand if...else.