C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Pattern Matching

C# Pattern Matching

Pattern matching lets you test a value against a pattern and extract information in one concise expression.

1 - is Pattern

object obj = "Hello, World!";

if (obj is string s)
    Console.WriteLine($"String of length {s.Length}");

if (obj is string { Length: > 5 } longStr)
    Console.WriteLine($"Long string: {longStr}");

2 - switch Expression (C# 8+)

public static string Classify(object obj) => obj switch
{
    int n when n < 0       => "negative int",
    int n when n == 0      => "zero",
    int n                  => $"positive int: {n}",
    string s when s == ""  => "empty string",
    string s               => $"string: {s}",
    null                   => "null",
    _                      => "something else"
};

Console.WriteLine(Classify(-5));    // negative int
Console.WriteLine(Classify("hi"));  // string: hi
Console.WriteLine(Classify(null));  // null

3 - Property Patterns

record Person(string Name, int Age, string Country);

static string GetDiscount(Person p) => p switch
{
    { Country: "US", Age: >= 65 } => "Senior US discount",
    { Country: "UK" }             => "UK discount",
    { Age: < 18 }                 => "Youth discount",
    _                             => "No discount"
};

Console.WriteLine(GetDiscount(new Person("Alice", 70, "US")));
// Senior US discount

4 - List Patterns (C# 11)

int[] arr = { 1, 2, 3 };

string result = arr switch
{
    []         => "empty",
    [var x]    => $"one element: {x}",
    [1, 2, ..] => "starts with 1, 2",
    _          => "other"
};
Console.WriteLine(result); // starts with 1, 2

Note: Switch expressions must be exhaustive — the compiler warns if not all cases are handled and there is no discard pattern (_). A missing discard becomes a runtime SwitchExpressionException.

-Tip-