Conditional Statements: if, else, and switch

Controlling program flow with decisions

Posted by Rodrigo Castro on October 25, 2024

Conditional statements let your program react to different situations.

✅ The if Statement

1
2
3
4
5
int score = 75;
if (score >= 60)
{
    Console.WriteLine("You passed!");
}

🛤️ The else Block

1
2
3
4
5
6
7
8
if (score >= 60)
{
    Console.WriteLine("You passed!");
}
else
{
    Console.WriteLine("Try again next time!");
}

➕ Multiple Conditions: else if

1
2
3
4
5
6
7
8
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: D or F");

🔀 The switch Statement

Handy for choosing between many options.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string color = "red";
switch (color)
{
    case "red":
        Console.WriteLine("Stop!");
        break;
    case "yellow":
        Console.WriteLine("Caution!");
        break;
    case "green":
        Console.WriteLine("Go!");
        break;
    default:
        Console.WriteLine("Unknown color.");
        break;
}

Early Return for Readability

In C#, using an early return can make your code easier to read and maintain by handling “exceptional” or edge cases first, and allowing the main logic to flow without deep nesting.

Example: Without early return

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void ProcessOrder(Order order)
{
    if (order != null)
    {
        if (order.IsValid)
        {
            // Main logic here
        }
        else
        {
            Console.WriteLine("Order is invalid.");
        }
    }
}

Example: With early return

1
2
3
4
5
6
7
8
9
10
void ProcessOrder(Order order)
{
    if (order == null) return;
    if (!order.IsValid)
    {
        Console.WriteLine("Order is invalid.");
        return;
    }
    // Main logic here
}

By returning early, you avoid unnecessary nesting and make the “happy path” more prominent and readable.

Advanced Switch Expressions in .NET 9

C# switch statements and expressions have evolved significantly. With .NET 9, the switch expression is even more powerful, allowing for advanced pattern matching, guards, and concise code.

Basic Switch Expression

1
2
3
4
5
6
7
8
string GetStatus(int code) =>
    code switch
    {
        200 => "OK",
        404 => "Not Found",
        500 => "Server Error",
        _   => "Unknown"
    };

Property Pattern Matching

1
2
3
4
5
6
7
8
string Describe(Person person) => person switch
{
    { Age: < 13 } => "Child",
    { Age: >= 13 and < 20 } => "Teenager",
    { Age: >= 20 } => "Adult",
    null => "Unknown",
    _ => "Invalid"
};

Relational Patterns and Logical Patterns

1
2
3
4
5
6
7
8
string Grade(int score) => score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};

List Patterns (C# 12 / .NET 9)

Switch can now directly match arrays and lists:

1
2
3
4
5
6
7
8
string Analyze(int[] numbers) => numbers switch
{
    [1, 2, 3] => "Sequence: 1, 2, 3",
    [_, _, 42] => "Three items, last is 42",
    [.., 7, 8, 9] => "Ends with 7, 8, 9",
    [var first, .., var last] => $"First: {first}, Last: {last}",
    _ => "Other"
};

Guards (when expressions)

1
2
3
4
5
6
string Classify(Person person) => person switch
{
    { Age: var age } when age < 0 => "Not born yet",
    { Age: var age } when age > 120 => "Unrealistic age",
    _ => "Normal"
};

Using early return and modern switch expressions can make your C# code cleaner, more concise, and easier to read (especially as your business logic grows in complexity).

💡 Try It!

Write a program that asks for a number (1-7) and prints the day of the week.

1
2
3
4
5
6
7
8
9
Console.Write("Enter a number (1-7): ");
int day = int.Parse(Console.ReadLine() ?? "1");
switch (day)
{
    case 1: Console.WriteLine("Sunday"); break;
    case 2: Console.WriteLine("Monday"); break;
    // ... etc.
    default: Console.WriteLine("Invalid day"); break;
}

Next up: Loops and iteration in C#!