0 day streak
csharp / intermediate
Snippet

Positional Pattern Matching and Deconstruction

Positional patterns allow you to match objects based on their deconstructed components. This works automatically with Records or classes that implement a Deconstruct method, providing a concise syntax for complex condition checks.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
public record Point(int X, int Y);
public string DescribeLocation(Point p) => p switch
{
(0, 0) => "At the origin",
(_, 0) => "On the X-axis",
(0, _) => "On the Y-axis",
var (x, y) when x == y => "On the diagonal",
_ => "Somewhere else"
};
Breakdown
1
p switch
Initiates a switch expression for the object p.
2
(_, 0)
Uses a discard pattern for X and matches if Y is exactly 0.
3
var (x, y) when x == y
Extracts values into variables and applies a guard clause condition.