Glossary / Pattern matching

Pattern matching

Pattern matching tests whether a value has a particular shape, type, constant, relational property, or combination of conditions, and can introduce variables for matched values. C# patterns make branching more expressive while allowing the compiler to analyze some exhaustiveness and reachability cases.

Pattern forms

C# includes constant, type, declaration, relational, logical (and, or, not), property, positional, list, and var patterns. Patterns appear in is expressions, switch statements/expressions, and case labels. Property patterns can inspect nested members; list patterns can match sequence shapes and slices in supported versions.

static string Describe(object? value) => value switch
{
    null => "missing",
    string { Length: 0 } => "empty text",
    string text => $"text: {text}",
    int number when number > 0 => "positive number",
    _ => "other"
};

A when guard adds a boolean condition after a pattern match. Logical pattern precedence and variable designation rules can be subtle; use parentheses and small cases for clarity. Property getters may execute code, so matching properties is not necessarily side-effect-free.

Exhaustiveness and design

Switch expressions should handle all intended cases; _ is a catch-all but can hide new variants. For closed discriminated hierarchies, explicit cases plus compiler warnings are valuable. Pattern matching does not validate untrusted input completely unless every required invariant is tested; type patterns only establish runtime type identity.

Interview questions

  1. What does a type pattern do? Tests runtime type and can bind a variable of the matched type.
  2. How does when differ? It adds a guard condition after the pattern succeeds.
  3. What is a list pattern? Matches sequence length/elements and optionally captures a slice.
  4. Can property patterns have side effects? Yes, property getters may execute arbitrary code.
  5. Why be cautious with _? It may silently absorb future variants and weaken exhaustiveness signals.

References