4. Conditionals

Conditionals choose which code runs. if / else if / else tests boolean conditions in order and runs the first block whose condition is true. A condition must be a bool: C# does not treat numbers or null as true or false. Conditions are combined with && (and), || (or) and ! (not), and blocks can be nested. With one statement the curly braces are optional, but always using braces avoids bugs when code is added later.

switch compares one value against several cases. In a classic switch statement each case must end with break (or return); several case labels can share one block, and default handles everything else. The modern switch expression returns a value and is shorter: each arm is pattern => result. Patterns can test constants, ranges (>= 90), combinations (and, or, not), types, properties and tuples, and a when clause adds an extra condition.

The ternary operator ?: is an inline if/else for choosing between two values. Pattern matching with is lets you test and cast in one step (if (o is string s)), and is null / is not null are the preferred ways to test for null.

Key points to remember

  • Order matters in an else-if chain: put the most specific or highest condition first.
  • Common mistake: a semicolon right after the if condition (if (x > 5); ) makes the block run unconditionally.
  • Common mistake: a classic switch case without break does not compile; C# does not allow silent fall-through (stacked empty case labels are fine).
  • A switch expression must handle every possible input; end it with the discard arm _ => ... or the compiler warns.
  • Use switch for one value with many exact matches or patterns, and if/else for ranges and unrelated conditions.
  • Prefer early returns (guard clauses) to deeply nested ifs: handle the invalid case first and return, then continue with the normal case.
  • Compare strings with string.Equals(a, b, StringComparison.OrdinalIgnoreCase) when case should not matter.

Example 1: if / else if / else

C#
int score = 72;
if (score >= 90) Console.WriteLine("A");
else if (score >= 70) Console.WriteLine("B");
else Console.WriteLine("C");
Show output Output
B

Example 2: Combining conditions and nesting

C#
int age = 20;
bool hasId = true;
bool isMember = false;

if (age >= 18 && hasId)
{
    if (isMember || age >= 65)
        Console.WriteLine("Discount entry");
    else
        Console.WriteLine("Normal entry");
}
else
{
    Console.WriteLine("Not allowed");
}

if (!(age < 13))
    Console.WriteLine("Not a young child");
Show output Output
Normal entry
Not a young child

Example 3: switch statement with grouped cases

C#
char grade = 'B';
switch (grade)
{
    case 'A':
    case 'B':                   // A and B share one block
        Console.WriteLine("Good");
        break;
    case 'C':
        Console.WriteLine("Average");
        break;
    default:
        Console.WriteLine("Unknown");
        break;
}

int day = 3;
switch (day)
{
    case 1: Console.WriteLine("Mon"); break;
    case 3: Console.WriteLine("Wed"); break;
    default: Console.WriteLine("Other"); break;
}
Show output Output
Good
Wed

Example 4: switch expression with relational patterns

C#
int score = 72;
string grade = score switch
{
    >= 90 => "A",
    >= 70 => "B",
    >= 50 => "C",
    _ => "F"
};
Console.WriteLine(grade);

int day = 6;
string type = day switch { 6 or 7 => "Weekend", _ => "Weekday" };
Console.WriteLine(type);
Show output Output
B
Weekend

Example 5: Type and property patterns with when

C#
static string Describe(object o) => o switch
{
    null => "nothing",
    int n when n < 0 => "negative int",
    int => "int",
    string s => $"string of length {s.Length}",
    _ => "something else"
};

Console.WriteLine(Describe(-3));
Console.WriteLine(Describe(5));
Console.WriteLine(Describe("hey"));
Console.WriteLine(Describe(null));
Console.WriteLine(Describe(2.5));
Show output Output
negative int
int
string of length 3
nothing
something else

Example 6: Tuple patterns

C#
static string Play(string a, string b) => (a, b) switch
{
    ("rock", "scissors") or ("paper", "rock") or ("scissors", "paper") => "Player 1 wins",
    (var x, var y) when x == y => "Draw",
    _ => "Player 2 wins"
};

Console.WriteLine(Play("rock", "scissors"));
Console.WriteLine(Play("paper", "paper"));
Console.WriteLine(Play("rock", "paper"));
Show output Output
Player 1 wins
Draw
Player 2 wins

Example 7: is patterns and null checks

C#
object value = "hello";

if (value is string text && text.Length > 3)
    Console.WriteLine("Long text: " + text);

string? name = null;
if (name is null) Console.WriteLine("No name");
if (name is not null) Console.WriteLine("Has name");

int n = 15;
if (n is > 10 and < 20) Console.WriteLine("Between 10 and 20");
Show output Output
Long text: hello
No name
Between 10 and 20

Example 8: Guard clauses and the ternary operator

C#
static string Classify(int? age)
{
    if (age is null) return "Unknown";      // handle bad input first
    if (age < 0) return "Invalid";
    return age < 18 ? "Minor" : "Adult";
}

Console.WriteLine(Classify(null));
Console.WriteLine(Classify(-5));
Console.WriteLine(Classify(12));
Console.WriteLine(Classify(30));
Show output Output
Unknown
Invalid
Minor
Adult