What if you could check complex data shapes with just one simple pattern instead of many lines of code?
Why Positional patterns in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a list of points with X and Y coordinates, and you want to check if each point lies on a specific line or shape by manually accessing each coordinate and writing many if-else statements.
This manual approach quickly becomes messy and hard to read. You have to write repetitive code to extract each coordinate and compare them, which is slow to write and easy to make mistakes in.
Positional patterns let you match and extract parts of data structures like tuples or records directly in a clear and concise way. This makes your code easier to read and maintain by focusing on the shape of the data.
if (point.X == 0 && point.Y == 0) { /* do something */ } else if (point.X == 1 && point.Y == 1) { /* do something else */ }
if (point is (0, 0)) { /* do something */ } else if (point is (1, 1)) { /* do something else */ }
You can write cleaner, more readable code that directly expresses the structure of your data and the conditions you want to check.
Checking the position of a chess piece on the board by matching its row and column coordinates to decide its possible moves.
Manual coordinate checks are repetitive and error-prone.
Positional patterns simplify matching data shapes directly.
They make your code clearer and easier to maintain.