Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 182 ยท Operators and Control Flow

if, else if and else

Learn C# if, else if and else statements - conditions, nesting, guard clauses, the ternary operator, simplifying boolean logic and the mistakes that trip up beginners.

A program that always does the same thing is not very useful. Real programs make decisions: show an error if the password is wrong, apply a discount if the cart is big enough, stop a game when the health bar reaches zero. In C# the basic tool for deciding is the if statement. It runs a block of code only when a condition is true.

This lesson covers if, else if and else, how conditions work (C# is stricter than some languages), how to keep nested decisions readable with guard clauses, when the ternary operator ?: is the better choice, and the mistakes that cause most bugs. You should already know the comparison and logical operators from the operators lesson.

The simplest decision: if

An if statement has a condition in parentheses and a statement or block after it. When the condition evaluates to true, the block runs. When it is false, the block is skipped.

C# A first if statement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line runs no matter what, because it sits outside the block. Change temperature to 20 and run the example again: only the final message appears.

The condition must be a bool

In C# the condition has to be a real bool. There is no "truthy" or "falsy" value like in JavaScript or C. A number, a string or an object is never accepted as a condition on its own:

C# A number is not a condition (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler stops with error CS0029: Cannot implicitly convert type 'int' to 'bool'. Write what you mean instead: if (count != 0). This rule removes a whole family of bugs that other languages allow. You can read more about the type in bool and char.

Always use braces

C# lets you skip the braces when the body is a single statement. Avoid that. Braces make the extent of the body obvious, and they protect you when you add a second line later:

C#
if (isAdmin)
    Console.WriteLine("Welcome, admin.");
    Console.WriteLine("Loading settings...");   // runs for EVERYONE

The indentation lies. Only the first WriteLine belongs to the if; the second always runs, and the compiler does not warn you. This course always uses braces, and so does nearly every professional C# codebase.

else: the other branch

Add else to handle the case where the condition is false. Exactly one of the two blocks runs, never both and never neither.

C# if with else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two things to notice. First, int.TryParse returns a bool and also gives you the parsed number through the out variable, so it is a perfect if condition. The variable age is declared right inside the condition, and it is usable inside both branches of that if. Second, the inner if is nested inside the first branch. Nesting is fine for a level or two, but it becomes hard to read quickly; we will fix that with guard clauses below.

The Input box is preset to 25. To test the other paths, change it to 12 or to some text such as abc.

else if: choosing among several options

When you have more than two cases, chain them with else if. C# checks the conditions from top to bottom and runs the first block whose condition is true. All the remaining branches are skipped, even if their conditions would also be true.

C# A grading ladder with else if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because the order matters, put the most restrictive or most likely condition first. In the ladder above, a score of 95 also satisfies score >= 80, but we never get there since the first test already matched. If you wrote the ladder in the opposite order (>= 60 first), every passing score would become a C. That is a very common bug.

Notice also that grade is assigned in every branch. The compiler uses "definite assignment" analysis: if a branch (including a missing final else) could leave the variable unassigned, using it afterward is an error (CS0165: Use of unassigned local variable). That makes the final else valuable: it proves to the compiler that every path sets the variable.

else if is not a special keyword. It is an else whose body is a single if statement, written without braces. That is the one place where skipping braces is traditional.

Combining conditions

Use && (and), || (or) and ! (not) to build bigger conditions. Both && and || are short-circuiting: the right side is evaluated only if it is still needed. That lets you write a safety check and the real check in a single condition:

C# Short-circuiting protects the second check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If name is null, the left operand is false, so name.Length is never evaluated and no NullReferenceException happens. Swap the two operands and the program crashes on the null entry. In real code you would use !string.IsNullOrEmpty(name), which does exactly this check, or the is not null pattern; see pattern matching basics.

Guard clauses: flatten your code

Deep nesting is the enemy of readable code. A guard clause checks for a bad situation first and leaves the method right away (with return, throw, continue or break). What remains is the "happy path" without extra indentation.

Compare these two versions of the same method:

C#
// Nested version: the real work is buried three levels deep
static decimal PriceNested(decimal basePrice, int quantity, bool isMember)
{
    if (quantity > 0)
    {
        if (basePrice >= 0)
        {
            decimal total = basePrice * quantity;
            if (isMember)
            {
                total *= 0.9m;
            }
            return total;
        }
        else
        {
            throw new ArgumentOutOfRangeException(nameof(basePrice));
        }
    }
    else
    {
        throw new ArgumentOutOfRangeException(nameof(quantity));
    }
}
C# The same method with guard clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The second version reads like a checklist: reject bad quantity, reject bad price, compute, apply the discount. Each condition is spelled in the negative ("what must not happen"), and the body has just one level of indentation. You will use this pattern constantly; the jumps lesson covers return, continue and break in more detail, and validating input goes deeper into argument checks.

if or the conditional operator?

The conditional (ternary) operator condition ? whenTrue : whenFalse is an expression: it produces a value. Use it when you need to choose between two values, and use if when you need to run different statements.

C# Choosing a value versus running statements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A single ternary is fine. A chain of two is borderline. Beyond that, switch to if / else if or a switch expression, which is designed for exactly this kind of mapping.

Simplifying boolean logic

Beginners often write code that works but says more than it needs to. Compare:

C#
// Wordy
if (isValid == true)
{
    return true;
}
else
{
    return false;
}

// Better
return isValid;

Three rules of thumb:

  • Never compare a bool with true or false. Write if (isValid) and if (!isValid).
  • When an if only returns or assigns true/false, return or assign the condition itself.
  • Use De Morgan's laws to simplify negated conditions: !(a && b) equals !a || !b, and !(a || b) equals !a && !b.
C# De Morgan's laws, checked by brute force

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

All four rows print same=True. Having proved it, you can rewrite if (!(age >= 18 && hasId)) as if (age < 18 || !hasId), which many people find easier to read.

Common mistakes

  • Assignment instead of comparison. In C#, if (x = 5) is a compile error for an int because the result is not a bool. For bool variables, though, if (done = true) compiles (with warning CS0665) and assigns. Write if (done).
  • A stray semicolon. if (x > 3); ends the statement at once, and the following block always runs. The compiler warns with CS0642 (possible mistaken empty statement). Treat that warning as an error.
  • Wrong order in an else-if ladder. Test the narrowest conditions first.
  • Comparing floating-point numbers with ==. 0.1 + 0.2 == 0.3 is false. Compare with a tolerance, or use decimal for money.
  • Forgetting that else binds to the nearest if. Without braces, a dangling else attaches to the closest if, not the one the indentation suggests. Braces remove the doubt.
  • Duplicated checks. If you test the same condition in three places, extract it into a well-named method or variable such as bool isEligible = age >= 18 && hasId;.

Name complex conditions. if (isEligible) tells the reader the intent; if (age >= 18 && hasId && !isBanned) forces them to decode it. A named bool local costs nothing at run time.

When something else is better

Too many else if branches comparing the same variable are a sign that a switch (statement or expression) will be clearer. Very long ladders that map a number to a label can often become a small lookup table. And when each branch calls a different behavior on an object, polymorphism (virtual methods) usually beats a pile of conditions. Use if for genuine yes/no decisions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which condition is valid in C#?

    C# requires the condition to be a bool. An int, a string or an assignment to an int is a compile error, while a comparison produces a bool.
  2. 2. In an if / else if / else ladder, several conditions are true. What runs?

    Conditions are tested from top to bottom, and after the first match the rest of the ladder is skipped.
  3. 3. What is the main benefit of a guard clause?

    A guard clause leaves the method early for invalid input, so the remaining code is the happy path with less nesting. It is about readability, not speed.
  4. 4. Why is name != null && name.Length > 0 safe when name is null?

    When the left operand of && is false, the result is already known, so the right operand is not evaluated and there is no NullReferenceException.
  5. 5. Which statement is the best way to write if (ok == true) { return true; } else { return false; }?

    When the condition is already a bool, return it directly. Comparing with true adds noise.

Summary

  • if runs a block when its condition is true; else handles the opposite case; else if chains further tests and only the first matching branch runs.
  • The condition must be a bool. C# has no truthy or falsy values.
  • Always use braces, and watch out for stray semicolons.
  • Order else-if ladders from the most specific condition to the most general one, and end with an else so variables are definitely assigned.
  • && and || short-circuit, which lets you put a safety check before the real check.
  • Guard clauses flatten nested code; the ternary operator picks between two values; name complex conditions.
  • Switch to a switch when many branches test the same value.

Next: switch Statements and Expressions