SyntaxStudy
Sign Up
C# If Statements and Switch Expressions
C# Beginner 1 min read

If Statements and Switch Expressions

C# supports all the familiar control-flow constructs: `if/else if/else`, `switch`, `for`, `foreach`, `while`, and `do/while`. Starting with C# 8, the language added switch expressions — a compact expression-based alternative to the traditional switch statement that returns a value rather than executing side effects. Switch expressions use the `=>` arm syntax and must be exhaustive: every possible input must match an arm or the compiler warns you. A discard pattern `_` acts as the default catch-all. Arms are evaluated in order; the first match wins. Conditional (ternary) expressions `condition ? a : b` are useful for inline decisions. C# 9 introduced the logical patterns `and`, `or`, and `not` for building compound match conditions without nested parentheses.
Example
// if/else, switch statement, and switch expression examples

int temperature = 22;

// Classic if/else
if (temperature < 0)
    Console.WriteLine("Freezing");
else if (temperature < 15)
    Console.WriteLine("Cold");
else if (temperature < 25)
    Console.WriteLine("Comfortable");
else
    Console.WriteLine("Hot");

// Traditional switch statement
DayOfWeek day = DayOfWeek.Wednesday;
switch (day)
{
    case DayOfWeek.Saturday:
    case DayOfWeek.Sunday:
        Console.WriteLine("Weekend");
        break;
    default:
        Console.WriteLine("Weekday");
        break;
}

// Switch expression (C# 8+) — returns a value
string description = temperature switch
{
    < 0             => "Freezing",
    >= 0 and < 15  => "Cold",
    >= 15 and < 25 => "Comfortable",
    _               => "Hot"
};
Console.WriteLine(description);

// Property pattern in switch expression
var point = (X: 0, Y: 5);
string quadrant = point switch
{
    (0, 0)             => "Origin",
    ( > 0,  > 0)       => "Q1",
    ( < 0,  > 0)       => "Q2",
    ( < 0,  < 0)       => "Q3",
    ( > 0,  < 0)       => "Q4",
    _                  => "On axis"
};
Console.WriteLine(quadrant); // "On axis"