0
0
CsharpConceptBeginner · 3 min read

Positional Pattern in C#: What It Is and How to Use It

In C#, a positional pattern lets you match an object by checking its components in order, like matching parts of a tuple or properties of a record. It uses parentheses to specify the values or patterns to match against the object's elements.
⚙️

How It Works

Think of a positional pattern as a way to check if an object fits a shape by looking at its parts one by one, in order. Imagine you have a box with several compartments, and you want to see if the items inside match a certain sequence. The positional pattern lets you do this by specifying what each compartment should hold.

In C#, this is often used with records or types that have a Deconstruct method. The pattern looks like a list of values inside parentheses, and the program compares each part of the object to the corresponding value or pattern you provide. If all parts match, the whole pattern matches.

💻

Example

This example shows a record Point with two coordinates. We use a positional pattern to check if a point is at the origin (0,0) or on the X or Y axis.

csharp
public record Point(int X, int Y);

class Program
{
    static string CheckPoint(Point p) => p switch
    {
        (0, 0) => "Origin",
        (var x, 0) => $"On X axis at {x}",
        (0, var y) => $"On Y axis at {y}",
        _ => "Somewhere else"
    };

    static void Main()
    {
        var points = new[] { new Point(0, 0), new Point(5, 0), new Point(0, 7), new Point(3, 4) };
        foreach (var point in points)
        {
            System.Console.WriteLine(CheckPoint(point));
        }
    }
}
Output
Origin On X axis at 5 On Y axis at 7 Somewhere else
🎯

When to Use

Use positional patterns when you want to check an object's parts quickly and clearly, especially with records or types that support deconstruction. They make your code easier to read and write when you need to match multiple values inside an object.

Common real-world uses include:

  • Checking coordinates or points in geometry.
  • Matching data in tuples or records.
  • Handling different cases in a switch expression based on object content.

Key Points

  • Positional patterns match objects by their parts in order.
  • They require the object to have a Deconstruct method or be a record.
  • They simplify complex switch or if statements.
  • They improve code readability by focusing on object structure.

Key Takeaways

Positional patterns let you match objects by their ordered parts using parentheses.
They work best with records or types that have a Deconstruct method.
Use them to write clear, concise code when checking multiple values inside an object.
They are commonly used in switch expressions for pattern matching.
Positional patterns improve readability and reduce boilerplate code.