Phase 4 of 30 · Topic 4.4

Recursive Pattern Matching & Guard Clauses (`when`)

1Concept

Recursive patterns drill into nested object graphs, combined with `when` conditional guards to validate business rules at compile-time safety.

2Architecture Diagram

Customer Record ──> Address ──> Country == "US"
                 └── LoyaltyTier ──> Level >= 3 (when AccountBalance > 0)
                                        │
                                        ▼
                         [ Trigger Priority Shipping ]

3Code Example

C# 13 & .NET 9
using System;

public record Address(string City, string Country);
public record Customer(string Name, Address Location, decimal Balance);

public class RecursivePatternDemo
{
    public static string DetermineEligibility(Customer customer) => customer switch
    {
        { Location: { Country: "US" }, Balance: >= 0 } when customer.Name.StartsWith("Corp") => "Approved US Enterprise Tier",
        { Location: { Country: "EU" } } => "Approved EU Standard Tier",
        _ => "Standard Application"
    };

    public static void Main()
    {
        var client = new Customer("CorpMegaTech", new Address("Seattle", "US"), 50_000m);
        Console.WriteLine($"Eligibility: {DetermineEligibility(client)}");
    }
}

4Expected Output

Eligibility: Approved US Enterprise Tier

5Key Takeaways

  • Recursive patterns check nested nulls safely without `NullReferenceException`.
  • `when` clauses allow runtime dynamic criteria to filter pattern matching branches.
  • Roslyn warns on unreachable patterns and incomplete exhaustiveness.