Positional patterns help you check the shape and values inside objects easily, like matching pieces in a puzzle.
0
0
Positional patterns in C Sharp (C#)
Introduction
When you want to check if an object has certain values in order.
When you want to write clear and simple code to compare parts of an object.
When you want to avoid writing many if statements to check each part separately.
Syntax
C Sharp (C#)
obj is TypeName(var1, var2, ...)
This checks if obj is of type TypeName and extracts parts into var1, var2, etc.
The type must have a Deconstruct method or be a record with positional parameters.
Examples
Checks if
point is a Point and extracts x and y values.C Sharp (C#)
point is Point(var x, var y)
Checks if
person is a Person and extracts name and age.C Sharp (C#)
person is Person(var name, var age)
Checks if
obj is a Point with x equal to 0 and extracts y.C Sharp (C#)
obj is Point(0, var y)Sample Program
This program creates a Point with X=0 and Y=5. It uses a positional pattern to check if X is 0 and extracts Y. Then it prints the result.
C Sharp (C#)
using System; record Point(int X, int Y); class Program { static void Main() { Point p = new(0, 5); if (p is Point(0, var y)) { Console.WriteLine($"X is zero and Y is {y}"); } else { Console.WriteLine("Point does not match pattern."); } } }
OutputSuccess
Important Notes
Positional patterns require the type to have a Deconstruct method or be a record with positional parameters.
You can mix constants and variables in the pattern to check specific values.
Summary
Positional patterns let you match and extract parts of an object easily.
They work well with records and types that have Deconstruct methods.
You can check values and get variables in one simple expression.