Course contentsShow
← C#
Lesson 49 of 1,9081. C# Language FoundationsFree lesson

Switch Expressions and Exhaustiveness

Ensure code correctness by verifying all branches are handled in functional switches.

In this lesson, you will learn how to write concise, functional logic using switch expressions while ensuring your code never misses a possible scenario.

From Statements to Expressions

In C#, a traditional switch statement is a control flow tool—it performs actions based on a value. A switch expression, introduced in more recent versions of the language, treats the switch as a calculation that returns a value. Because it is an expression, it is much more compact and fits neatly into assignments or return statements.

Consider this example where we convert a simple status code into a human-readable message:

string message = status switch
{
    0 => "Success",
    1 => "Pending",
    2 => "Error",
    _ => "Unknown Status" // The discard pattern
};

The Rule of Exhaustiveness

The most powerful feature of a switch expression is exhaustiveness. The C# compiler acts as your safety net: it forces you to handle every possible input value. If you forget to account for a specific input, the compiler will generate an error, preventing potential bugs at runtime.

The underscore _ is known as the discard pattern. It acts as a "catch-all" for any values not explicitly defined above it. If you are switching on an enum, the compiler is even smarter—it knows the specific set of defined constants. If you miss one, the build will fail until you add it.

Why use this over a statement?

  1. Brevity: You avoid the repetitive case, break, and return keywords.
  2. Safety: You cannot accidentally forget to handle a case; the compiler enforces exhaustiveness.
  3. Immutability: Since it is an expression, you can assign the result directly to a variable without needing a mutable variable defined outside the scope of your logic.

By using switch expressions, you shift the burden of checking for missing logic from your manual testing to the compiler's static analysis.

Key Takeaway: Switch expressions allow you to assign values based on pattern matching with a compiler-guaranteed safety net that forces you to handle every possible input.