Recursion in C# – Theory & Practice

Study backup for exams – understand recursion with real examples.

What is Recursion?

Recursion means that a method calls itself to solve a smaller part of a problem.

Key Concepts:

Structure Example:

void Recurse(int x)
{
    if (x == 0) return;     // Base case
    Recurse(x - 1);         // Recursive call
}

Advantages:

Disadvantages:

Example 1 – Recursive File Scanner

Recursively collects all files from a directory and its subdirectories.

List<FileEntry> Scan(string path)
{
    var list = new List<FileEntry>();

    foreach (var file in Directory.GetFiles(path))
        list.Add(new FileEntry { FullPath = file });

    foreach (var dir in Directory.GetDirectories(path))
        list.AddRange(Scan(dir)); // Recursive call

    return list;
}

Example 2 – Build a Directory Tree

Convert flat path strings into a nested tree structure.

TreeNode Build(List<string> paths)
{
    var root = new TreeNode { Name = "ROOT" };

    foreach (var p in paths)
    {
        var parts = p.Split('\\');
        var curr = root;

        foreach (var part in parts)
        {
            var next = curr.Children.FirstOrDefault(c => c.Name == part);
            if (next == null)
                curr.Children.Add(next = new TreeNode { Name = part });

            curr = next;
        }
    }

    return root;
}

Example 3 – Print Tree Recursively

Recursively prints a directory tree with indentation.

void Print(TreeNode node, string indent = "")
{
    Console.WriteLine(indent + node.Name);

    foreach (var child in node.Children)
        Print(child, indent + "  "); // Recursive call
}