0
0
C Sharp (C#)programming~30 mins

Recursive pattern matching in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Recursive Pattern Matching
📖 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#)
Need a 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#)
Need a 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#)
Need a 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#)
Need a hint?

Use the ternary operator inside Console.WriteLine to print the result.