Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Positional patterns in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Positional Patterns Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of positional pattern matching with tuples
What is the output of this C# code using positional patterns with tuples?
C Sharp (C#)
var point = (X: 3, Y: 4);
string result = point switch
{
    (0, 0) => "Origin",
    (var x, 0) => $"X={x}, on X-axis",
    (0, var y) => $"Y={y}, on Y-axis",
    (var x, var y) => $"Point at ({x},{y})"
};
Console.WriteLine(result);
AX=3, on X-axis
BY=4, on Y-axis
CPoint at (3,4)
DOrigin
Attempts:
2 left
💡 Hint
Think about which pattern matches the tuple (3,4) first.
❓ Predict Output
intermediate
2:00remaining
Pattern matching with positional records
Given the record and code below, what is the output?
C Sharp (C#)
record Person(string FirstName, string LastName);

var person = new Person("Alice", "Smith");
string greeting = person switch
{
    ("Alice", "Smith") => "Hello Alice Smith!",
    ("Bob", _) => "Hello Bob!",
    _ => "Hello stranger!"
};
Console.WriteLine(greeting);
AHello Alice Smith!
BHello Bob!
CHello stranger!
DCompilation error
Attempts:
2 left
💡 Hint
Check which positional pattern matches the Person record.
🔧 Debug
advanced
2:00remaining
Positional pattern matching with guards on records
What is the output of this code?
C Sharp (C#)
record Point(int X, int Y);

var p = new Point(1, 2);
string result = p switch
{
    (var x, var y) when x > y => "X is greater",
    (var x, var y) when y > x => "Y is greater",
    (var x, var y) when x == y => "Equal",
    _ => "Unknown"
};
Console.WriteLine(result);
AOutput: Y is greater
BCompilation error: positional patterns not supported on records
CRuntime error: NullReferenceException
DOutput: X is greater
Attempts:
2 left
💡 Hint
Records support positional patterns via generated Deconstruct methods. For (1,2), evaluate the when conditions in order.
❓ Predict Output
advanced
2:00remaining
Output of nested positional patterns
What is the output of this code with nested positional patterns?
C Sharp (C#)
record Rectangle(Point TopLeft, Point BottomRight);
record Point(int X, int Y);

var rect = new Rectangle(new Point(0, 0), new Point(5, 5));
string description = rect switch
{
    (var (x1, y1), var (x2, y2)) when x1 == 0 && y1 == 0 && x2 == 5 && y2 == 5 => "Standard 5x5 rectangle",
    _ => "Other rectangle"
};
Console.WriteLine(description);
ARuntime error
BOther rectangle
CCompilation error
DStandard 5x5 rectangle
Attempts:
2 left
💡 Hint
Look at how nested positional patterns match the record properties.
❓ Predict Output
expert
3:00remaining
Output of positional pattern with deconstruction and discard
What is the output of this code using positional patterns with discard (_) and deconstruction?
C Sharp (C#)
record Color(int R, int G, int B);

Color c = new(255, 0, 0);
string result = c switch
{
    (255, 0, 0) => "Red",
    (0, 255, 0) => "Green",
    (0, 0, 255) => "Blue",
    (var r, var g, var b) when r == g && g == b => "Gray",
    _ => "Unknown color"
};
Console.WriteLine(result);
AGray
BRed
CUnknown color
DGreen
Attempts:
2 left
💡 Hint
Check which positional pattern matches the color (255,0,0).

Practice

(1/5)
1.

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:

easy
A. Extract values of X and Y from a Point object easily
B. Create a new Point object with given X and Y
C. Change the values of X and Y in the Point object
D. Call a method named Deconstruct on the Point object

Solution

  1. Step 1: Understand positional pattern usage

    Positional patterns allow matching an object and extracting its parts in one step, like case Point(var x, var y):.
  2. 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.
  3. Final Answer:

    Extract values of X and Y from a Point object easily -> Option A
  4. Quick Check:

    Positional pattern extracts values [OK]
Hint: Positional patterns extract parts of an object [OK]
Common Mistakes:
  • Thinking positional patterns create or modify objects
  • Confusing Deconstruct method call with pattern matching
  • Assuming positional patterns only check types without extracting
2.

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;
}
easy
A. Person(var name, var age)
B. Person[name, age]
C. Person{name, age}
D. Person(name: name, age: age)

Solution

  1. Step 1: Recall positional pattern syntax

    Positional patterns use parentheses with variables: Type(var1, var2).
  2. 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.
  3. Final Answer:

    Person(var name, var age) -> Option A
  4. Quick Check:

    Positional pattern syntax uses parentheses [OK]
Hint: Positional patterns always use parentheses, not brackets or braces [OK]
Common Mistakes:
  • Using square brackets or curly braces instead of parentheses
  • Trying to use named arguments syntax inside patterns
  • Omitting var keyword or variable names
3.

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;
}
medium
A. Origin
B. Point at (3, 4)
C. On diagonal
D. No output

Solution

  1. Step 1: Check first case Point(0, 0)

    p is (3,4), so it does not match (0,0).
  2. Step 2: Check second case with condition x == y

    x=3, y=4, so x != y; condition fails.
  3. Step 3: Third case matches any Point and prints coordinates

    It matches and prints "Point at (3, 4)".
  4. Final Answer:

    Point at (3, 4) -> Option B
  5. Quick Check:

    Pattern matches last case with output [OK]
Hint: Check cases top to bottom; first match runs [OK]
Common Mistakes:
  • Assuming (3,4) matches (0,0)
  • Ignoring the when condition in second case
  • Thinking no case matches and no output
4.

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;
}
medium
A. Switch expression cannot use records
B. First case should use named arguments instead of positional pattern
C. Second case uses variables without var keyword, causing a syntax error
D. No error, code runs fine

Solution

  1. Step 1: Review positional pattern variable declaration

    Variables in positional patterns must be declared with var or a type.
  2. Step 2: Identify error in second case

    Second case uses Rectangle(w, h) without var, which is invalid syntax.
  3. Final Answer:

    Second case uses variables without var keyword, causing a syntax error -> Option C
  4. Quick Check:

    Variables need var keyword in patterns [OK]
Hint: Always declare variables with var in positional patterns [OK]
Common Mistakes:
  • Omitting var keyword for variables in patterns
  • Thinking records can't be used in switch
  • Confusing named arguments with pattern variables
5.

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?

hard
A. person switch { Person(_, var age) when age < 13 => "Child", Person(_, var age) when age > 13 && age <= 19 => "Teen", Person(_, _) => "Adult" };
B. person switch { Person(var name, var age) when age < 13 => "Child", Person(var name, var age) when age > 13 && age < 19 => "Teen", _ => "Adult" };
C. 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" };
D. 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" };

Solution

  1. Step 1: Check age ranges and conditions

    Child: age < 13, Teen: 13 ≤ age ≤ 19, Adult: otherwise.
  2. 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 uses age < 13 for Child, age >= 13 && age <= 19 for 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.
  3. 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.
  4. Final Answer:

    Option D code correctly implements the age groups -> Option D
  5. Quick Check:

    Check age ranges carefully in when clauses [OK]
Hint: Check boundary conditions carefully in when clauses [OK]
Common Mistakes:
  • Overlapping or missing age boundaries
  • Using _ wildcard instead of variables when needed
  • Incorrect logical operators in conditions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard