📖 Scenario: Imagine you have a simple tree structure representing folders and files. Each folder can contain files or other folders. You want to find if a specific file exists anywhere inside this tree.
🎯 Goal: Build a C# program that uses recursive pattern matching to check if a file with a given name exists inside a nested folder structure.
📋 What You'll Learn
Create a record type File with a Name property.
Create a record type Folder with a Name property and a list of Items which can be File or Folder.
Write a recursive method ContainsFile that uses pattern matching to check if a file with a given name exists in the folder or any subfolder.
Print "Found" if the file exists, otherwise "Not Found".
💡 Why This Matters
🌍 Real World
File systems and many applications use nested folder structures. Searching files inside them is a common task.
💼 Career
Understanding recursive pattern matching helps in writing clean, readable code for complex data structures like trees, useful in software development and data processing jobs.
Progress0 / 4 steps
1
Create the data structure
Create a record called File with a string property Name, and a record called Folder with a string property Name and a list of objects called Items.
C Sharp (C#)
Hint
Use C# 9+ record syntax to create simple data containers.
2
Create sample folder data
Create a variable root of type Folder representing a folder named "root" that contains a File named "readme.txt" and a subfolder named "docs" which contains a File named "manual.pdf".
C Sharp (C#)
Hint
Use nested lists to represent folders inside folders.
3
Write the recursive pattern matching method
Write a method bool ContainsFile(Folder folder, string fileName) that uses a foreach loop and recursive pattern matching with switch expressions to check if any File with Name equal to fileName exists in folder or its subfolders.
C Sharp (C#)
Hint
Use switch with pattern matching and recursion to check nested folders.
4
Print the search result
Write a Console.WriteLine statement that prints "Found" if ContainsFile(root, "manual.pdf") returns true, otherwise prints "Not Found".
C Sharp (C#)
Hint
Use the ternary operator inside Console.WriteLine to print the result.
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
Recursive pattern matching is used to analyze data by breaking it down into smaller parts recursively.
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.
Final Answer:
To break down complex data structures step-by-step -> Option A
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
Step 1: Recall C# recursive pattern syntax
In C#, recursive patterns use parentheses with variables inside, like Node(var value, var next).
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.
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
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.
Step 2: Verify syntax correctness
The pattern syntax and semicolons are correct. No syntax errors exist.
Final Answer:
No error, code works correctly -> Option B
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
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.
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.
Final Answer:
node switch { null => 0, TreeNode(var v, var l, var r) => v + Sum(l) + Sum(r) } -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.