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

Recursive pattern matching in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Recursive Pattern Matching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of recursive pattern matching with nested tuples
What is the output of this C# code using recursive pattern matching on nested tuples?
C Sharp (C#)
using System;

class Program {
    static string Describe((int, (int, int)) data) => data switch {
        (0, (0, 0)) => "All zeros",
        (var x, (var y, var z)) when x == y && y == z => "All equal",
        (var x, (_, var z)) when x > z => "First greater than last",
        _ => "Other"
    };

    static void Main() {
        Console.WriteLine(Describe((0, (0, 0))));
        Console.WriteLine(Describe((3, (3, 3))));
        Console.WriteLine(Describe((5, (1, 2))));
        Console.WriteLine(Describe((1, (2, 3))));
    }
}
A
All zeros
All equal
Other
First greater than last
B
All zeros
All equal
First greater than last
Other
C
Other
All equal
First greater than last
Other
D
All zeros
Other
First greater than last
Other
Attempts:
2 left
💡 Hint
Look carefully at the pattern conditions and the order they are checked.
🧠 Conceptual
intermediate
1:30remaining
Understanding recursive pattern matching with lists
Given this C# recursive pattern matching on a list, what is the value of result after execution?
C Sharp (C#)
using System;
using System.Collections.Generic;

class Program {
    static int SumList(List<int> list) => list switch {
        [] => 0,
        [var head, .. var tail] => head + SumList(tail)
    };

    static void Main() {
        var numbers = new List<int> {1, 2, 3};
        var result = SumList(numbers);
        Console.WriteLine(result);
    }
}
A3
B0
C6
DCompilation error
Attempts:
2 left
💡 Hint
Think about how the list is split into head and tail recursively.
🔧 Debug
advanced
1:30remaining
Identify the runtime error in recursive pattern matching
What runtime error will this C# code produce when executed?
C Sharp (C#)
using System;

class Program {
    static int Factorial(int n) => n switch {
        0 => 1,
        > 0 => n * Factorial(n - 1),
        _ => throw new ArgumentException("Negative input")
    };

    static void Main() {
        Console.WriteLine(Factorial(-1));
    }
}
ASystem.ArgumentException: Negative input
BStackOverflowException
CNo output, program runs fine
DSystem.InvalidOperationException
Attempts:
2 left
💡 Hint
Check which pattern matches negative input and what it does.
📝 Syntax
advanced
1:30remaining
Which option causes a syntax error in recursive pattern matching?
Which of the following C# code snippets will cause a syntax error due to incorrect recursive pattern matching syntax?
Aint Sum((int head, int tail) data) => data switch { var (h, t) => h + t };
Bint Sum((int head, int tail) data) => data switch { (var h, var t) => h + t };
Cint Sum((int head, (int, int) tail) data) => data switch { (var h, (var t1, var t2)) => h + t1 + t2 };
Dint Sum((int head, int tail) data) => data switch { (var h, var t) => h + t, };
Attempts:
2 left
💡 Hint
Check the pattern syntax for tuples inside switch expressions.
🚀 Application
expert
2:30remaining
Calculate depth of nested tuples using recursive pattern matching
What is the output of this C# program that calculates the depth of nested tuples using recursive pattern matching?
C Sharp (C#)
using System;

class Program {
    static int Depth(object obj) => obj switch {
        (var l, var r) => 1 + Math.Max(Depth(l), Depth(r)),
        _ => 0
    };

    static void Main() {
        var nested = ((1, (2, 3)), (4, 5));
        Console.WriteLine(Depth(nested));
    }
}
ACompilation error
B2
C4
D3
Attempts:
2 left
💡 Hint
Count how many levels of nested tuples are inside the variable.

Practice

(1/5)
1. What is the main purpose of recursive pattern matching in C#?
easy
A. To break down complex data structures step-by-step
B. To create loops that run forever
C. To declare variables without types
D. To handle exceptions automatically

Solution

  1. Step 1: Understand recursive pattern matching concept

    Recursive pattern matching is used to analyze data by breaking it down into smaller parts recursively.
  2. Step 2: Identify the purpose from options

    To break down complex data structures step-by-step correctly states that it breaks down complex data structures step-by-step, which matches the concept.
  3. Final Answer:

    To break down complex data structures step-by-step -> Option A
  4. Quick Check:

    Recursive pattern matching = step-by-step data breakdown [OK]
Hint: Think: recursive means breaking down data stepwise [OK]
Common Mistakes:
  • Confusing recursion with infinite loops
  • Thinking it declares variables
  • Assuming it handles exceptions
2. Which of the following is the correct syntax to use recursive pattern matching in a C# switch expression?
easy
A. case Node(var value, var next):
B. case Node[value, next]:
C. case Node->(value, next):
D. case Node[value; next]:

Solution

  1. Step 1: Recall C# recursive pattern syntax

    In C#, recursive patterns use parentheses with variables inside, like Node(var value, var next).
  2. Step 2: Compare options to correct syntax

    case Node(var value, var next): matches the correct syntax. Other options use invalid symbols like brackets or arrows.
  3. Final Answer:

    case Node(var value, var next): -> Option A
  4. Quick Check:

    Recursive pattern syntax uses parentheses ( ) [OK]
Hint: Look for parentheses with variables inside in case patterns [OK]
Common Mistakes:
  • Using square brackets instead of parentheses
  • Using arrows or semicolons incorrectly
  • Missing 'var' keyword before variables
3. What will be the output of this C# code snippet?
record Node(int Value, Node? Next);
Node list = new(1, new(2, new(3, null)));

string PrintList(Node? node) => node switch
{
null => "End",
Node(var v, var n) => $"{v} -> " + PrintList(n)
};

Console.WriteLine(PrintList(list));
medium
A. 1 2 3 End
B. End
C. 1 -> 2 -> 3 -> End
D. 1 -> 2 -> 3

Solution

  1. Step 1: Understand the recursive function PrintList

    PrintList prints the current node's value, then calls itself on the next node, until it reaches null and returns "End".
  2. Step 2: Trace the output for list nodes 1, 2, 3

    It prints "1 -> " + PrintList(2), then "2 -> " + PrintList(3), then "3 -> " + PrintList(null), which returns "End".
  3. Final Answer:

    1 -> 2 -> 3 -> End -> Option C
  4. Quick Check:

    Recursive print with null base case = 1 -> 2 -> 3 -> End [OK]
Hint: Follow recursion calls and base case carefully [OK]
Common Mistakes:
  • Ignoring the base case output
  • Missing arrows in output
  • Confusing spaces with arrows
4. Identify the error in this recursive pattern matching code:
record Node(int Value, Node? Next);
string PrintList(Node? node) => node switch
{
Node(var v, var n) => $"{v} -> " + PrintList(n),
null => "End"
};
medium
A. Missing semicolon after switch expression
B. No error, code works correctly
C. The pattern 'Node(var v, var n)' is invalid syntax
D. The order of cases should have 'null' before 'Node' to avoid errors

Solution

  1. Step 1: Check switch expression order and syntax

    In C#, switch expressions check patterns top to bottom. Here, 'Node' pattern matches non-null nodes, and 'null' matches null nodes. The order is valid.
  2. Step 2: Verify syntax correctness

    The pattern syntax and semicolons are correct. No syntax errors exist.
  3. Final Answer:

    No error, code works correctly -> Option B
  4. Quick Check:

    Pattern order and syntax are valid [OK]
Hint: Null pattern can be last in switch expressions [OK]
Common Mistakes:
  • Thinking null must come first
  • Assuming missing semicolon error
  • Misreading pattern syntax
5. Given a binary tree defined as:
record TreeNode(int Value, TreeNode? Left, TreeNode? Right);

Write a recursive pattern matching expression to calculate the sum of all values in the tree. Which of the following switch expressions correctly implements this?
hard
A. node switch { null => 0, TreeNode(v, l, r) => v + Sum(l) + Sum(r) }
B. node switch { TreeNode(v, l, r) => v + Sum(l) + Sum(r), null => 0 }
C. node switch { null => 0, TreeNode(var v, var l) => v + Sum(l) }
D. node switch { null => 0, TreeNode(var v, var l, var r) => v + Sum(l) + Sum(r) }

Solution

  1. Step 1: Understand the tree structure and sum logic

    The tree node has three parts: Value, Left, and Right. The sum should add the current value plus sums of left and right subtrees.
  2. Step 2: Check each option for correct pattern and order

    node switch { null => 0, TreeNode(var v, var l, var r) => v + Sum(l) + Sum(r) } correctly matches null first (base case) and then TreeNode with three variables (value, left, right). It sums value + Sum(left) + Sum(right). node switch { TreeNode(v, l, r) => v + Sum(l) + Sum(r), null => 0 } misses 'var' keywords, which is required. node switch { null => 0, TreeNode(v, l, r) => v + Sum(l) + Sum(r) } misses 'var' keywords, which is required. node switch { null => 0, TreeNode(var v, var l) => v + Sum(l) } misses the right subtree.
  3. Final Answer:

    node switch { null => 0, TreeNode(var v, var l, var r) => v + Sum(l) + Sum(r) } -> Option D
  4. Quick Check:

    Correct pattern with all parts and base case first [OK]
Hint: Include all node parts and base case null first [OK]
Common Mistakes:
  • Omitting 'var' in pattern variables
  • Missing one subtree in sum
  • Placing null case after non-null without care
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