C# Positional Pattern — Complete Guide
In this tutorial, you'll learn about C# Positional Pattern. We cover key concepts, practical examples, and best practices.
You have a tuple or an object with a Deconstruct method and you want to match its components in a switch expression. You write nested conditions to extract and compare each part individually. Positional patterns let you match on the decomposed shape directly.
Wrong
var point = (3, 4);
if (point.Item1 == 0 && point.Item2 == 0) Console.WriteLine("Origin");
else if (point.Item1 > 0 && point.Item2 == 0) Console.WriteLine("On X axis");
Output: Works but verbose. Does not scale with more complex shapes.
Right
var point = (3, 4);
var description = point switch
{
(0, 0) => "Origin",
( > 0, 0) => "On positive X axis",
(0, > 0) => "On positive Y axis",
var (x, y) => $"At ({x}, {y})"
};
Console.WriteLine(description);
Output: "At (3, 4)".
The positional pattern (0, 0) matches a tuple or object at position 0,0. For custom types, implement Deconstruct:
public record struct Point(int X, int Y);
// Deconstruct is automatic for records
Point p = new(3, 4);
var result = p switch { (0, 0) => "Origin", _ => "Other" };
Prevention
- Use positional patterns with tuples for quick multi-value matching.
- Implement
Deconstructon your types to enable positional matching. - Use records — they auto-generate
Deconstruct. - Combine with
whenclauses for additional conditions. - Use
varpatterns to capture and name the deconstructed values. - Nest positional patterns:
( > 0, ( "admin" or "user" )).
Common Mistakes with positional pattern
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Positional patterns are used in DodaZIP to match archive entry headers by their byte positions. For more C# patterns, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro