Codiqo

Learn C# · lesson 15 of 61 · about 8 minutes

else if and Nesting

Roll for loot: choose between several outcomes with else if, catch impossible values first, and put decisions inside decisions.

What you'll learn

  • Chain conditions with else if
  • Order conditions correctly
  • Nest if statements

More than two outcomes

After the fight, the hero rolls a 20-sided die for loot: 18 or more finds a big potion, 10 or more finds arrows, and anything lower finds only slime. That's three outcomes, and if with else only gives two.

else if adds more conditions. They're checked from the top, only the first true branch runs, and else catches whatever is left.

The loot roll

int roll = 12;
if (roll >= 18)
{
    Console.WriteLine("Rare loot: a big potion!");
}
else if (roll >= 10)
{
    Console.WriteLine("Loot: 5 arrows");
}
else
{
    Console.WriteLine("Loot: just slime");
}

Output

Loot: 5 arrows

Order matters

Check in one direction. Here that's the highest roll first: if roll >= 10 came first, a 19 would match it and the hero would only get arrows. And check impossible values before anything else: a d20 only shows 1 to 20, and int.TryParse gives 0 for anything that isn't a number, so roll < 1 || roll > 20 goes at the top.

Weather advice

int temp = 14;
bool raining = true;
if (temp >= 25)
{
    Console.WriteLine("Shorts weather");
}
else if (temp >= 12)
{
    Console.WriteLine("Jacket weather");
    if (raining)
    {
        Console.WriteLine("Take an umbrella");
    }
}
else
{
    Console.WriteLine("Coat weather");
}

Output

Jacket weather
Take an umbrella

Tip

C# has no elif: it's two words, else if.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.