.NET Academy

Making decisions with if / else

Run different code depending on conditions, from simple checks to chains of rules.

10 min read

You will learn

  • Write if, else if and else blocks
  • Combine conditions correctly
  • Use guard clauses to keep code flat
  • Use the ternary operator for simple choices

Programs that choose

So far our programs ran every line from top to bottom. Real programs make decisions: show an error if the password is wrong, apply a discount for students, skip empty lines. The if statement runs a block of code only when a condition is true.

int temperature = 32;
 
if (temperature > 30)
{
    Console.WriteLine("It's hot — drink water!");
}

The condition inside the parentheses must be a bool expression — a comparison, a bool variable, or a combination with &&, ||, !.

else: the other path

if (balance >= price)
{
    Console.WriteLine("Purchase approved");
}
else
{
    Console.WriteLine("Insufficient funds");
}

Exactly one of the two blocks runs.

else if: chains of rules

if (temperature > 30)
{
    Console.WriteLine("Hot");
}
else if (temperature > 20)
{
    Console.WriteLine("Warm");      // only checked if the first condition was false
}
else if (temperature > 10)
{
    Console.WriteLine("Mild");
}
else
{
    Console.WriteLine("Cold");
}

C# checks the conditions in order and runs the first block whose condition is true. Order matters: if you checked > 10 first, 35 °C would print "Mild".

Combining conditions

if (age >= 18 && hasTicket)                // both must be true
    Console.WriteLine("Welcome in");
 
if (day == "Saturday" || day == "Sunday")  // either is enough
    Console.WriteLine("Weekend!");
 
if (!isLoggedIn)                           // negation
    Console.WriteLine("Please log in");

Always use braces

C# allows a single statement without { }, as above — but if you later add a second line, only the first one is inside the if. Using braces everywhere avoids that whole class of bugs.

Guard clauses: fail fast, stay flat

Nested ifs quickly become hard to read:

string Describe(int score)
{
    if (score >= 0)
    {
        if (score <= 100)
        {
            if (score >= 50) return "pass";
            else return "fail";
        }
    }
    return "invalid";
}

Handle the edge cases first with early returns, and the main logic stays at the top level:

string Describe(int score)
{
    if (score < 0 || score > 100) return "invalid";   // guard clause
 
    return score >= 50 ? "pass" : "fail";
}

The ternary operator

For a simple either/or value, use condition ? whenTrue : whenFalse:

string label = age >= 18 ? "adult" : "minor";
int shipping = total >= 50 ? 0 : 5;
Console.WriteLine($"You have {count} {(count == 1 ? "item" : "items")}");

Keep ternaries short — if you need to nest them, an if or a switch (next lesson) is clearer.

Try it

Change temperature and isRaining and see which message appears:

Program.cs
Loading editor…

C# runtime not loaded

Key takeaways

  • if runs a block when its condition is true; else handles the other case.
  • In an else if chain, the first true condition wins — order your checks carefully.
  • Guard clauses handle invalid input early and keep code flat.
  • ?: picks between two values in one expression.

Exercise

Grade turns a score into a letter: 90+ → "A", 80+ → "B", 70+ → "C", 60+ → "D", otherwise "F". Scores below 0 or above 100 are "Invalid". Max3 returns the largest of three numbers (write it with if statements — no Math.Max).

Program.cs
Loading editor…

C# runtime not loaded

Hint 1

Check for invalid scores first (a guard clause), then go from the highest grade down.

Hint 2

Because each else-if is only reached when the previous conditions were false, `else if (score >= 80)` already knows score < 90.

Hint 3

For Max3: start with `int max = a;` then update max if b or c is bigger.

Show solution
string Grade(int score)
{
    if (score < 0 || score > 100) return "Invalid";

    if (score >= 90) return "A";
    else if (score >= 80) return "B";
    else if (score >= 70) return "C";
    else if (score >= 60) return "D";
    else return "F";
}

int Max3(int a, int b, int c)
{
    int max = a;
    if (b > max) max = b;
    if (c > max) max = c;
    return max;
}

Console.WriteLine(Grade(95));
Console.WriteLine(Max3(1, 7, 3));

Quiz

4 questions · 3 correct to pass
  1. 1.With `int t = 25;`, what does this print? `if (t > 30) Console.Write("hot"); else if (t > 20) Console.Write("warm"); else Console.Write("cold");`

  2. 2.What does `string label = age >= 18 ? "adult" : "minor";` do?

  3. 3.Why are braces `{ }` recommended even for one-line if bodies?

  4. 4.What's a guard clause?

To complete this lesson

  • ○ Solve the exercise
  • ○ Pass the quiz (3/4 correct)