C# ยท Chapter 16 of 46

C# If ... Else

The if statement lets your program make decisions by executing code only when a condition is true. You can add else if to check additional conditions, and else to run code when none of the conditions are true.

Conditions inside if statements must evaluate to a bool. This is a fundamental building block of program logic, letting programs respond differently depending on input or data.

Syntax
if (condition) {
  // code
} else if (condition2) {
  // code
} else {
  // code
}

if, else if, else

An if statement runs a block only if its condition is true. else if lets you check another condition if the first was false, and else runs when none of the previous conditions matched.

Ternary operator

The ternary operator `condition ? valueIfTrue : valueIfFalse` is a compact way to write a simple if/else that returns a value.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int age = 20;
    if (age >= 18) {
      Console.WriteLine("Adult");
    } else {
      Console.WriteLine("Minor");
    }
  }
}
Output
Adult

Since age is 20, which is >= 18, the if block runs.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    int score = 75;
    string grade = score >= 90 ? "A" : score >= 70 ? "B" : "C";
    Console.WriteLine(grade);
  }
}
Output
B

The ternary operator chains to check multiple ranges and assigns the matching grade.

Key points

  • if runs code only when its condition is true.
  • else if checks additional conditions in sequence.
  • else runs when no previous condition was true.
  • The ternary operator ?: is a shorthand for simple if/else.
๐Ÿ’ก Note: Only one branch of an if/else if/else chain will run โ€” once a condition matches, the rest are skipped.

๐Ÿ“ Quick Quiz

1. What must an if condition evaluate to?

2. When does the else block run?

3. What is the ternary operator used for?