Codiqo

Learn C# · lesson 14 of 61 · about 7 minutes

if and else

Let the Slime fight back: run code only when a condition is true, give an alternative with else, and keep every branch in braces.

What you'll learn

  • Write an if statement
  • Add an else branch
  • Use braces for every branch

Doing something about it

Your battle knows how much HP the Slime has left, in left, but the Slime never does anything about it. if (condition) { ... } runs its block only when the condition is true, and else { ... } runs otherwise. The condition goes in round brackets, and each block goes in braces.

The Slime hits back, or it doesn't

int heroHp = 30;
int left = 1;
if (left > 0)
{
    heroHp -= 4;
    Console.WriteLine($"The Slime hits back! Hero HP: {heroHp}");
}
else
{
    Console.WriteLine("The Slime is defeated!");
}
Console.WriteLine("Next turn.");

Output

The Slime hits back! Hero HP: 26
Next turn.

Always use braces

Without braces, an if only guards the one statement after it. Indenting a second line doesn't put it inside: C# ignores indentation. Worse, an else after two unbraced lines doesn't compile at all, because the if already ended. Braces on every branch avoid both problems, even when a branch is one line long.

Tip

In C# the condition must be a real bool. if (left) with an int doesn't compile: write the question out, like if (left > 0). C# style puts each brace on its own line.

Now try it yourself

This lesson is free in Codiqo, with 10 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.