Language 4 of 10 · Topic 0.5

Control Flow: Switch Expressions & Recursive Pattern Matching

1Concept

C# pattern matching switch expressions (val switch { Pattern => Result }) support relational patterns, property patterns, type tests, and list patterns with concise, expressive syntax.

2Architecture Diagram

var message = order switch {
    { Total: > 1000, IsVip: true } => "Priority Fast Shipping",
    { Total: > 500 }               => "Standard Free Shipping",
    _                              => "Standard Shipping"
};

3Code Example

Stage 0 Language Foundations
using System;

public record Order(int Id, decimal Total, bool IsVip, string Country);

class Program
{
    public static string CalculateShipping(Order order) => order switch
    {
        { IsVip: true } => "VIP Complimentary Next-Day Air",
        { Total: >= 1000m, Country: "US" } => "US Free Freight Express",
        { Total: >= 500m } => "Standard Free Shipping",
        { Total: < 500m } => "Flat Rate $15 Ground Shipping",
        _ => "Standard Shipping"
    };

    static void Main()
    {
        var o1 = new Order(101, 1200m, false, "US");
        var o2 = new Order(102, 250m, true, "IN");
        var o3 = new Order(103, 150m, false, "UK");

        Console.WriteLine($"Order #1: {CalculateShipping(o1)}");
        Console.WriteLine($"Order #2: {CalculateShipping(o2)}");
        Console.WriteLine($"Order #3: {CalculateShipping(o3)}");
    }
}

4Expected Output

Order #1: US Free Freight Express
Order #2: VIP Complimentary Next-Day Air
Order #3: Flat Rate $15 Ground Shipping

5Key Takeaways

  • Switch expressions return values and require no break statements.
  • Property patterns ({ Prop: value }) inspect object properties cleanly.
  • The discard pattern _ serves as the default fallback.