Exhaustive switch and null cases
Exhaustive switch and null cases
A switch expression maps one input to a result through ordered arms of the form pattern when condition => result. The guard is optional. The first matching arm whose guard succeeds supplies the result. Unlike a switch statement, the expression produces a value. Include a discard arm _ when the domain has possible values not covered by earlier patterns. The discard matches null too, so put a dedicated null arm before it if absence has different meaning.
Exhaustiveness means that every possible input is covered, not merely every example or named enum member. A fallback can return a documented unknown state or throw for invalid input; do not disguise an impossible state as a success. The compiler warns about many non-exhaustive switch expressions, and an unmatched value throws at runtime. A subsumed arm can be a compile error.
using System;Console.WriteLine(Describe(new Ready(3)));Console.WriteLine(Describe(new Failed("offline")));Console.WriteLine(Describe(null));Console.WriteLine(Describe(new Ready(0)));static string Describe(JobState? state) => state switch{ null => "Missing", Ready { Count: > 0 } r => $"Ready {r.Count}", Failed => "Failed", _ => "Unsupported"};abstract record JobState;record Ready(int Count) : JobState;record Failed(string Reason) : JobState;The Ready arm deliberately handles only positive counts. A Ready with zero falls through to the fallback. Other derived states are also possible because the base hierarchy is not a closed union.
Expected output (reasoned, not executed):
Ready 3FailedMissingUnsupportedPlace narrow guarded arms before general ones
using System;Console.WriteLine(Fee("East", 5));Console.WriteLine(Fee("East", 6));Console.WriteLine(Fee("West", 2));static int Fee(string zone, int boxes) => (zone, boxes) switch{ (_, <= 0) => throw new ArgumentOutOfRangeException(nameof(boxes)), ("East", var n) when n <= 5 => 2, ("East", _) => 4, _ => 8};The first arm rejects nonpositive quantities. The guard distinguishes the smaller East order. Placing the general East arm first would make the narrower guarded case unreachable.
Expected output (reasoned, not executed):
248Handle unnamed enum values
using System;Console.WriteLine(Label(Status.Open));Console.WriteLine(Label((Status)99));static string Label(Status status) => status switch{ Status.Open => "Open", Status.Closed => "Closed", _ => "Unknown"};enum Status { Open, Closed }Enums can contain underlying numeric values without declared names. The discard arm handles 99 even though it is not a named member. A two-arm expression would not cover all possible values.
Expected output (reasoned, not executed):
OpenUnknownCommon mistakes and edge cases
Do not put a catch-all before special cases. An arm that covers all values of a later unguarded pattern makes the later arm unreachable. Guards are not equivalent to a static proof of completeness. A non-exhaustive switch expression on .NET can throw SwitchExpressionException when no arm matches. Inspect the separate diagnostic example for an intentionally incomplete expression; it is not a positive test. Prefer a fallback that communicates a meaningful policy instead of silently returning a valid-looking value.
Practice and next steps
Write a switch expression Label(int? score) that returns Missing for null, Invalid outside 0–100, Pass for 60–100, and Retry for 0–59. Test null, -1, 0, 59, 60, 100, 101.
Next: Generic methods and types.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exhaustive switch and null cases — knowledge check
Apply the lesson concepts to the following scenarios.
Which arm handles an input?
Does `_` match null in a switch expression?
Why include a fallback for an enum with all named members listed?
What can happen when no switch expression arm matches?
Why place a special East order before the general East pattern?