If / Else: The Crossroads

If / Else: The Crossroads in C#: A program runs in a straight line until it reaches a fork. is the signpost there: it asks one yes-or-no question and sends…

The Analogy: The Signpost at a Fork

A program runs in a straight line until it reaches a fork. if is the signpost there: it asks one yes-or-no question and sends control down one road or the other. else if adds further forks a little way along the same road, and else is the road taken when every signpost has said no.

The important property of a fork is that only one road is travelled. In an if / else if / else chain the tests are tried top to bottom, the first one that answers yes runs its block, and the rest are never even asked. That ordering is not a detail; it is the whole meaning of the chain, and putting the loosest test first is the single most common way to break one.

C# insists the question be a genuine yes-or-no. There is no truthiness here: a number is not a question, and neither is an object. if (count) does not compile, which prevents a family of C bugs at the cost of typing != 0.


Syntax or Core Structure

using System;

class Program
{
    static void Main()
    {
        int score = 82;

        if (score >= 90)
        {
            Console.WriteLine("grade A");
        }
        else if (score >= 80)
        {
            Console.WriteLine("grade B");
        }
        else if (score >= 70)
        {
            Console.WriteLine("grade C");
        }
        else
        {
            Console.WriteLine("grade F");
        }

        bool passed = score >= 60;
        string status = passed ? "pass" : "fail";
        Console.WriteLine($"score {score}: {status}");

        int stock = 0;
        if (stock == 0 && passed)
            Console.WriteLine("passed but out of stock");

        string? note = null;
        Console.WriteLine($"note length: {note?.Length ?? -1}");

        if (score is >= 80 and < 90)
            Console.WriteLine("solidly in the B band");
    }
}

Output:

grade B
score 82: pass
passed but out of stock
note length: -1
solidly in the B band

The chain stops at the first match: 82 fails >= 90, matches >= 80, and the >= 70 test never runs even though it would also have been true.

passed ? "pass" : "fail" is the conditional operator. It is an expression, so it produces a value, which is why it can sit on the right of an assignment where an if statement cannot. Both branches must have compatible types.

score is >= 80 and < 90 is a relational pattern, available from C# 9. It is the closest C# comes to the chained comparison 80 <= score < 90 that other languages allow and C# rejects.


Technical Depth: Building the Condition

The operators you have to hand

OperatorMeaningNote
== !=equal, not equalon string this compares contents, not references
< <= > >=orderingnumbers, DateTime, anything IComparable
&& `\\`and, orshort-circuit: the right side may never run
& `\`and, orboth sides always evaluated
!notreads badly when stacked; prefer a positive name
istype or pattern testx is int n, x is >= 0, x is null
?? ?.null fallback, null-safe accessnote?.Length ?? -1

Short-circuiting is not an optimisation you can ignore — it is load-bearing:

if (name != null && name.Length > 3)   // safe: Length is only read when name is not null
if (name != null &  name.Length > 3)   // NullReferenceException when name is null

The single & evaluates both operands before combining them. Use && and || unless you specifically want both sides to run.

The condition must be bool

int count = 0;
if (count) { }              // ERROR: cannot convert int to bool
if (count != 0) { }         // fine

bool ready = false;
if (ready = true) { }       // COMPILES. Assigns, then tests. Always true.
if (ready == true) { }      // works, but just write: if (ready)

The middle line is the one to watch. Because ready = true is an assignment expression of type bool, the compiler accepts it, the variable is overwritten, and the branch always runs. Writing if (ready) rather than if (ready == true) removes the chance of typing it.

Comparing the awkward types

string a = "Ok", b = "ok";
Console.WriteLine(a == b);                                        // False
Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // True

double x = 0.1 + 0.2;
Console.WriteLine(x == 0.3);                    // False
Console.WriteLine(Math.Abs(x - 0.3) < 1e-9);    // True

== on strings compares contents, which is the behaviour Java programmers expect from .equals and often get wrong in reverse. For case-insensitive work pass a StringComparison instead of calling ToLower() on both sides — it allocates nothing and behaves predictably across cultures.

Two doubles that "should" be equal frequently are not. Compare with a tolerance, or use decimal where exactness matters.

Guard clauses beat nesting

// nested: the real work is four levels deep
static decimal Discount(Order? order)
{
    if (order != null)
        if (order.Items.Count > 0)
            if (order.Total > 100m)
                return order.Total * 0.1m;
    return 0m;
}

// guarded: each precondition is stated and dismissed
static decimal Discount(Order? order)
{
    if (order is null) return 0m;
    if (order.Items.Count == 0) return 0m;
    if (order.Total <= 100m) return 0m;

    return order.Total * 0.1m;
}

Both compute the same thing. The second version keeps the interesting line at the left margin and lets a reader stop caring about each edge case as soon as they have read it — the reason guard clauses are the house style in most C# codebases.

Naming a condition

if (user.Age >= 18 && user.Country == "UK" && !user.IsSuspended && user.Verified)

bool canPurchase = user.Age >= 18
                   && user.Country == "UK"
                   && !user.IsSuspended
                   && user.Verified;
if (canPurchase)

The second form costs one line and gives the rule a name that appears in the debugger and in error messages. When a condition needs a comment to explain it, it wanted a name instead.


Real World Example: A Shipping Rule

Shipping cost is decided by four facts and half a dozen rules, which is exactly the size at which if starts to need discipline.

using System;

class Program
{
    const decimal FreeShippingFrom = 50.00m;
    const decimal FlatRate = 4.99m;
    const decimal HeavySurcharge = 7.50m;

    static decimal Shipping(decimal orderTotal, double weightKg,
                            string country, bool isMember)
    {
        if (orderTotal <= 0m)
            return 0m;                                   // nothing to ship

        bool domestic = string.Equals(country, "UK", StringComparison.OrdinalIgnoreCase);
        if (!domestic)
            return FlatRate * 3m;                        // one international rate

        bool shipsFree = orderTotal >= FreeShippingFrom || isMember;
        decimal cost = shipsFree ? 0m : FlatRate;

        if (weightKg > 20.0)
            cost += HeavySurcharge;                      // applies even when free

        return cost;
    }

    static void Main()
    {
        (decimal total, double kg, string country, bool member)[] orders =
        {
            (72.40m,  3.0, "UK", false),
            (18.00m,  1.2, "UK", false),
            (18.00m,  1.2, "uk", true),
            (18.00m, 24.5, "UK", true),
            (95.00m,  2.0, "DE", false),
            ( 0.00m,  0.0, "UK", false),
        };

        foreach (var o in orders)
        {
            decimal ship = Shipping(o.total, o.kg, o.country, o.member);
            string label = ship == 0m ? "free" : ship.ToString("F2");

            Console.WriteLine($"{o.total,7:F2}{o.kg,7:F1}  {o.country,-3}" +
                              $"{(o.member ? "member" : "guest"),-7} -> {label}");
        }
    }
}

Output:

  72.40    3.0  UK guest   -> free
  18.00    1.2  UK guest   -> 4.99
  18.00    1.2  uk member  -> free
  18.00   24.5  UK member  -> 7.50
  95.00    2.0  DE guest   -> 14.97
   0.00    0.0  UK guest   -> free

Row by row: the first qualifies on total, the second qualifies on nothing and pays the flat rate, the third is free because membership is an alternative route to free shipping, the fourth is free and heavy so it pays only the surcharge, the fifth is international at three times the flat rate, and the sixth is an empty order that leaves through the first guard.

Three of the rules are named rather than inlined. domestic, shipsFree and the three const values mean the body of the method reads as the policy document it implements. A reviewer can check the rules without decoding any arithmetic.

string.Equals(..., StringComparison.OrdinalIgnoreCase) is why "uk" works. A plain country == "UK" would have charged that customer the international rate — the sort of bug that reaches production because the test data was all uppercase.

The heavy surcharge is added after the free-shipping decision, not inside it. That ordering is the business rule: free shipping waives the base rate but not the surcharge. Written as one large boolean expression the distinction would be invisible.

(o.member ? "member" : "guest"),-7 needs the parentheses. Inside an interpolation hole a bare : starts the format string, so the conditional operator has to be wrapped before the alignment specifier can follow it.


Common Mistakes

  1. Ordering the chain from loosest to tightest. Testing score >= 70 before score >= 90 means every high score is graded C, because the first matching branch wins. Write the narrowest condition first.
  2. = where == was meant. if (isReady = true) compiles, assigns, and always runs the branch. Test a bool directly — if (isReady) — and the typo becomes impossible.
  3. Dropping the braces and then adding a second statement. if (x) DoA(); DoB(); runs DoB() unconditionally however it is indented. This is the shape of the real-world "goto fail" bug; always brace multi-line bodies.
  4. Using & or | instead of && and ||. The non-short-circuiting forms evaluate both sides, so a null check placed on the left no longer protects the right.
  5. Comparing double values with ==. 0.1 + 0.2 == 0.3 is false. Compare with a tolerance, or use decimal.
  6. Chaining comparisons. if (0 < x < 10) does not compile in C#: the first comparison yields a bool, which cannot be compared to 10. Write 0 < x && x < 10, or x is > 0 and < 10.
  7. Case-sensitive string comparison by accident. country == "UK" rejects "uk". Use string.Equals with StringComparison.OrdinalIgnoreCase rather than lowercasing both operands.
  8. Checking a property before checking for null. if (order.Total > 0 && order != null) throws, because the operands are evaluated left to right. The null test must come first.

Best Practices

  • Use guard clauses to reject invalid input at the top of a method and keep the main path unindented. Nesting deeper than two levels is a signal to restructure.
  • Always brace bodies that span more than one line, and stay consistent within a file. A single-line if (x is null) return; is idiomatic and fine.
  • Give complex conditions a name. A bool canPurchase = ... line reads better than a four-clause if and shows up usefully in a debugger.
  • Prefer positive conditions. if (isValid) is easier to reason about than if (!isInvalid), and double negatives are where logic bugs hide.
  • Reach for a switch once a chain tests the same value more than three times. The next lesson covers it, and the compiler can then check that you covered every case.
  • Use patterns rather than arithmetic where they read better: x is null, obj is string s, age is >= 18 and < 65.
  • Use string.IsNullOrWhiteSpace(s) instead of hand-rolling s == null || s.Trim() == "". It is clearer and handles every whitespace character.
  • Make else cover a real case. An else that only exists to log "should not happen" is often better as a thrown exception, so the impossible case fails loudly rather than quietly.

Practice Exercises

  1. Write a method static string Band(int score) returning "A", "B", "C" or "F" by the boundaries in this lesson, then call it for { 95, 90, 89, 80, 70, 69, 0 } and print each score with its band. Check the boundary values specifically.
  2. Take a nested three-level if of your own writing and rewrite it with guard clauses so the successful path is at the left margin. Keep both versions and confirm they agree for every input you can think of.
  3. Extend the shipping rule with a bool isFragile flag that adds a fixed 2.50 handling fee, and a rule that international orders never ship free. Add two rows to the table that exercise the new behaviour and hand-check the expected output before you run it.
  4. Write a comparison playground: for a = "Straße", b = "STRASSE" and x = 0.1 + 0.2, print the results of a == b, the ordinal-ignore-case comparison, x == 0.3, and a tolerance comparison. Write one sentence on which result surprised you.