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.
Practice
What is the main purpose of positional patterns in C#?
record Point(int X, int Y);
Using case Point(var x, var y): inside a switch statement helps to:
Solution
Step 1: Understand positional pattern usage
Positional patterns allow matching an object and extracting its parts in one step, likecase Point(var x, var y):.Step 2: Identify what the pattern does with Point
It extracts the X and Y values from the Point object into variables x and y for use inside the case block.Final Answer:
Extract values of X and Y from a Point object easily -> Option AQuick Check:
Positional pattern extracts values [OK]
- Thinking positional patterns create or modify objects
- Confusing Deconstruct method call with pattern matching
- Assuming positional patterns only check types without extracting
Which of the following is the correct syntax for using a positional pattern with a record Person(string Name, int Age) inside a switch expression?
switch(person) {
case ???:
// code
break;
}Solution
Step 1: Recall positional pattern syntax
Positional patterns use parentheses with variables:Type(var1, var2).Step 2: Match syntax to options
Person(var name, var age) uses parentheses and variables correctly:Person(var name, var age). Others use invalid syntax for positional patterns.Final Answer:
Person(var name, var age) -> Option AQuick Check:
Positional pattern syntax uses parentheses [OK]
- Using square brackets or curly braces instead of parentheses
- Trying to use named arguments syntax inside patterns
- Omitting var keyword or variable names
What is the output of the following code?
record Point(int X, int Y);
var p = new Point(3, 4);
switch (p)
{
case Point(0, 0):
Console.WriteLine("Origin");
break;
case Point(var x, var y) when x == y:
Console.WriteLine("On diagonal");
break;
case Point(var x, var y):
Console.WriteLine($"Point at ({x}, {y})");
break;
}Solution
Step 1: Check first case Point(0, 0)
p is (3,4), so it does not match (0,0).Step 2: Check second case with condition x == y
x=3, y=4, so x != y; condition fails.Step 3: Third case matches any Point and prints coordinates
It matches and prints "Point at (3, 4)".Final Answer:
Point at (3, 4) -> Option BQuick Check:
Pattern matches last case with output [OK]
- Assuming (3,4) matches (0,0)
- Ignoring the when condition in second case
- Thinking no case matches and no output
Identify the error in this code snippet using positional patterns:
record Rectangle(int Width, int Height);
var rect = new Rectangle(5, 10);
switch(rect)
{
case Rectangle(var w, var h):
Console.WriteLine($"Width: {w}, Height: {h}");
break;
case Rectangle(w, h):
Console.WriteLine("Invalid pattern");
break;
}Solution
Step 1: Review positional pattern variable declaration
Variables in positional patterns must be declared withvaror a type.Step 2: Identify error in second case
Second case usesRectangle(w, h)withoutvar, which is invalid syntax.Final Answer:
Second case uses variables without var keyword, causing a syntax error -> Option CQuick Check:
Variables need var keyword in patterns [OK]
- Omitting var keyword for variables in patterns
- Thinking records can't be used in switch
- Confusing named arguments with pattern variables
Given the record Person(string Name, int Age), write a switch expression using positional patterns that returns:
- "Child" if Age < 13
- "Teen" if Age is between 13 and 19 inclusive
- "Adult" otherwise
Which of the following switch expressions correctly implements this?
Solution
Step 1: Check age ranges and conditions
Child: age < 13, Teen: 13 ≤ age ≤ 19, Adult: otherwise.Step 2: Analyze each option's conditions
person switch { Person(var name, var age) when age < 13 => "Child", Person(var name, var age) when age >= 13 && age <= 19 => "Teen", Person(var name, var age) => "Adult" }; correctly usesage < 13for Child,age >= 13 && age <= 19for Teen, and default Adult case. person switch { Person(_, var age) when age < 13 => "Child", Person(_, var age) when age > 13 && age <= 19 => "Teen", Person(_, _) => "Adult" }; misses age=13 (falls to Adult) because Teen condition uses > 13. person switch { Person(var name, var age) when age < 13 => "Child", Person(var name, var age) when age > 13 && age < 19 => "Teen", _ => "Adult" }; excludes age == 13 and 19 for Teen. person switch { Person(var name, var age) when age <= 13 => "Child", Person(var name, var age) when age >= 13 && age <= 19 => "Teen", Person(var name, var age) => "Adult" }; overlaps Child and Teen at age 13.Step 3: Confirm the correct implementation
person switch { Person(var name, var age) when age < 13 => "Child", Person(var name, var age) when age >= 13 && age <= 19 => "Teen", Person(var name, var age) => "Adult" }; matches all conditions correctly and clearly.Final Answer:
Option D code correctly implements the age groups -> Option DQuick Check:
Check age ranges carefully in when clauses [OK]
- Overlapping or missing age boundaries
- Using _ wildcard instead of variables when needed
- Incorrect logical operators in conditions
Ready to prove it?
Pass the test and this pattern moves unknown
