Skip to content

List patterns C# 11.0code reductionreadability

Match arrays and lists against sequences of patterns.

Pattern matching in earlier C# versions could match on type, properties, and relational conditions but had no way to match against the structure of a sequence such as an array or list.

C# 11 introduces list patterns that let you match elements at specific positions, use the discard _ to skip elements, and the slice .. to match zero or more elements.

Code ​

csharp
string Classify(int[] numbers) => numbers switch
{
    [] => "empty",
    [var single] => $"one element: {single}",
    [0, .., > 0] => "starts with zero and ends positive",
    [_, _] => "exactly two elements",
    [.., < 0] => "ends with a negative number",
    _ => "something else"
};

// Slice patterns can capture into a variable
if (data is [var first, .. var rest])
{
    Process(first, rest);
}
csharp
string Classify(int[] numbers)
{
    if (numbers.Length == 0)
        return "empty";
    if (numbers.Length == 1)
        return $"one element: {numbers[0]}";
    if (numbers[0] == 0 && numbers[^1] > 0)
        return "starts with zero and ends positive";
    if (numbers.Length == 2)
        return "exactly two elements";
    if (numbers[^1] < 0)
        return "ends with a negative number";
    return "something else";
}

Notes ​

  • Works with any type that is countable and indexable, including arrays, List<T>, and Span<T>
  • The slice pattern .. matches zero or more elements; capturing them (.. var rest) also requires the type to support slicing with a range indexer or a Slice method
  • Can be combined with other patterns such as relational, property, and type patterns
  • A null input fails to match any list pattern rather than throwing, so the Now version returns "something else" for null where the Before version throws
  • See Recursive pattern matching C# 8.0 for matching on properties and positions, which list patterns extend to sequence length and contents.
  • See Pattern match Span on string constants C# 11.0 for the separate case of matching a span against a string constant.
  • See the pattern matching across versions guide for the other pattern kinds available alongside list patterns.

More information ​

Powered by Intracia