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

C#
string Classify(int[] numbers) => numbers switch
{
    [] => "empty",
    [var single] => $"one element: {single}",
    [_, _] => "exactly two elements",
    [0, .., > 0] => "starts with zero and ends positive",
    [.., < 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);
}
C#
string Classify(int[] numbers)
{
    if (numbers.Length == 0)
        return "empty";
    if (numbers.Length == 1)
        return $"one element: {numbers[0]}";
    if (numbers.Length == 2)
        return "exactly two elements";
    if (numbers[0] == 0 && numbers[^1] > 0)
        return "starts with zero and ends positive";
    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 and can optionally capture them
  • Can be combined with other patterns such as relational, property, and type patterns

More information