Pattern matching

2 min read

Pattern matching (C# 7.0+) gives a more expressive, concise syntax for testing whether an expression has a certain “shape”, such as a specific type or specific property values, and, if it does, extracting information from it. It’s commonly used in is expressions and in switch statements and expressions. It moves beyond simple value equality checks, to a more declarative way of interrogating data structures.

Type pattern

The type pattern checks the runtime type of an expression and, if it matches, casts it to that type.

C#
if (obj is string s) Console.WriteLine(s.ToUpper());

Property pattern

The property pattern matches an expression on the values of its properties or fields. The first line is a recordRecordsA class for immutable data, with value-based equality generated for you.Opens in a new tab, and the pattern is on the second.

C#
public record Point(int X, int Y);if (shape is Point { X: 0, Y: 0 }) Console.WriteLine("Point is at origin");

Tuple pattern

The tuple pattern matches deconstructed tuple elements. The tuple patterns are on lines 3 and 4. The _ on line 5 is the discard pattern, covered below.

C#
string GetQuadrant((int x, int y) point) => point switch{    (> 0, > 0) => "First",    (< 0, > 0) => "Second",    _ => "Other or on axis"};

Positional pattern

The positional pattern is used with types that have a deconstructor, and matches on the deconstructed values.

Discard pattern (_)

The discard pattern matches any expression, but discards its value. It’s useful when you only care about certain parts of a pattern.

Where it matters

Pattern matching significantly reduces boilerplate code for type checks and conditional logic. It makes code more readable and less error-prone than traditional if-else chains or manual type casting.

The relational, logical and list patterns are in the next noteRelational, logical and list patternsCompare with operators, combine patterns, and match the elements of a list.Opens in a new tab, and switch expressions are in their ownSwitch expressionsA switch that returns a value.Opens in a new tab.


Sources