Lesson 3 · ~12 min · ← Lesson 2

Making decisions: if, else, switch

Programs get interesting when they react. C# has exactly three shapes of choosing — the chain, the table, and the one-liner — and one golden rule: conditions are always bool.

if: ask a yes/no question

int temperature = 22;

if (temperature > 30)
{
    Console.WriteLine("too hot");     // not reached: 22 is not > 30
}
else
{
    Console.WriteLine("temperature is fine");
}

else if: a chain of checkpoints

The chain runs top to bottom and stops at the FIRST true condition — order matters:

int score = 85;

if (score >= 90)
{
    Console.WriteLine("A");
}
else if (score >= 80)      // reached only because score >= 90 was false
{
    Console.WriteLine("B");
}
else if (score >= 70)
{
    Console.WriteLine("C");
}
else
{
    Console.WriteLine("F");
}

Combining questions: && and ||

&& = "and" (both must hold). || = "or" (at least one). ! = "not". They short-circuit: the moment the answer is known, the rest isn't even evaluated.

int day = 6;          // Saturday
bool holiday = false;

if (day == 6 || day == 7)
{
    Console.WriteLine("weekend, enjoy!");
}

if (day == 6 && !holiday)     // && needs BOTH sides true
{
    Console.WriteLine("personal project time");
}
else
{
    Console.WriteLine("not a holiday");
}

The golden rule: conditions are bool, nothing else

Coming from C, C++ or JavaScript? This trips everyone: if (1) is a compile error in C#. A number is not a truth value:

int count = 3;
if (count)   // error CS0029: Cannot implicitly convert type 'int' to 'bool'
{
    Console.WriteLine("three");
}
int count = 3;
if (count == 3)   // say what you mean: a comparison produces a bool
{
    Console.WriteLine("three");
}

switch: one value, many exact matches

When you compare the SAME expression against many constants, switch reads cleaner than an else if chain:

string order = "espresso";

switch (order)
{
    case "espresso":
        Console.WriteLine("espresso — small and strong");
        break;
    case "latte":
    case "cappuccino":              // stacked labels: two orders, one recipe
        Console.WriteLine("milky and large");
        break;
    default:
        Console.WriteLine("unknown order");
        break;
}

The one law of C# switch: every non-empty case ends in break;, return; or throw;. Forgetting it is error CS0163 — C# refuses the "fall-through" that caused so many C bugs.

The ternary: an if that fits in one expression

int age = 20;
string status = age >= 18 ? "adult" : "minor";   // condition ? if-true : if-false
Console.WriteLine(status);
Console.WriteLine(15 >= 18 ? "adult" : "minor");

Use it when both branches produce a value. The moment you're tempted to nest a ternary inside a ternary — write a real if, your future self says thanks.

Practice this now