SyntaxStudy
Sign Up
C# Beginner 1 min read

Pattern Matching

Pattern matching in C# lets you test a value against a shape and extract data in a single operation. It started with simple type patterns in C# 7 (`is` expressions) and has grown into a powerful system covering constant patterns, relational patterns, logical patterns, property patterns, positional patterns, and list patterns (C# 11). The `is` keyword can be used both for type-testing with binding (`obj is string s`) and for more complex patterns. Switch expressions and switch statements both support the full pattern vocabulary, making them much more expressive than their traditional counterparts. List patterns allow you to match on the structure of an array or list: `[1, 2, ..]` matches any list starting with 1 and 2. The slice pattern `..` matches zero or more elements and can optionally be bound to a variable. These patterns integrate naturally with deconstruction and property matching.
Example
// Pattern matching examples

object[] items = { 42, "hello", 3.14, true, null!, new List<int> { 1, 2 } };

foreach (var item in items)
{
    string result = item switch
    {
        int n when n > 0        => $"Positive int: {n}",
        int n                   => $"Non-positive int: {n}",
        string { Length: > 3 } s => $"Long string: {s}",
        string s                => $"Short string: {s}",
        double d                => $"Double: {d:F2}",
        bool b                  => $"Bool: {b}",
        null                    => "null value",
        _                       => $"Other: {item.GetType().Name}"
    };
    Console.WriteLine(result);
}

// Property pattern
record Person(string Name, int Age, string Country);
var alice = new Person("Alice", 30, "UK");

string category = alice switch
{
    { Age: < 18 }                           => "Minor",
    { Country: "UK", Age: >= 18 }           => "UK Adult",
    { Age: >= 65 }                          => "Senior",
    _                                        => "Adult"
};
Console.WriteLine(category); // "UK Adult"

// List pattern (C# 11)
int[] nums = { 1, 2, 3, 4, 5 };
bool matched = nums is [1, 2, .. var rest] && rest.Length > 0;
Console.WriteLine(matched); // True