0
0
C Sharp (C#)programming~3 mins

Why Positional patterns in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could check complex data shapes with just one simple pattern instead of many lines of code?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
if (point.X == 0 && point.Y == 0) { /* do something */ } else if (point.X == 1 && point.Y == 1) { /* do something else */ }
After
if (point is (0, 0)) { /* do something */ } else if (point is (1, 1)) { /* do something else */ }
What It Enables

You can write cleaner, more readable code that directly expresses the structure of your data and the conditions you want to check.

Real Life Example

Checking the position of a chess piece on the board by matching its row and column coordinates to decide its possible moves.

Key Takeaways

Manual coordinate checks are repetitive and error-prone.

Positional patterns simplify matching data shapes directly.

They make your code clearer and easier to maintain.