Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 182 ยท Pattern Matching and Modern C#

List and Slice Patterns

Learn C# 11 list patterns and slice patterns - match arrays, lists, strings and spans by shape with [first, .., last], capture slices with var, and write small parsers.

Until C# 11, pattern matching could look at the shape of an object (its type and properties) but not at the shape of a sequence. If you wanted to know "is this array exactly [1, 2, 3]?" or "does this command start with add, followed by anything?", you wrote length checks and index lookups by hand. List patterns close that gap: they let you describe the elements of an array, a list or even a string in the same declarative style you already use for properties.

This lesson covers the list pattern itself, the slice pattern .. that matches "any number of elements", capturing slices into variables, using list patterns with strings and spans, and a few practical uses such as command parsing and recursion over lists. It assumes you know the basics from Pattern Matching Basics and Pattern Matching in Depth, and that you are comfortable with ranges and indices.

Matching exact sequences

A list pattern is a comma-separated list of subpatterns in square brackets. It matches when the input has exactly that many elements and each element matches its subpattern.

C# Exact list patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each position accepts any pattern you already know: constants, relational patterns, _ (any one element), var x (capture one element), property patterns and more. The empty pattern [] matches an empty sequence.

For a type to work with list patterns it must be countable (a Length or Count property) and indexable (an int indexer). Arrays, List<T>, string, Span<T>, ImmutableArray<T> and most collections qualify. Plain IEnumerable<T> does not (it has no count and no indexer), so convert it with ToArray() or ToList() first.

The slice pattern

The slice pattern .. matches zero or more elements. You may use it at most once in a list pattern. It turns an exact-length test into "starts with", "ends with" or "contains at the edges".

C# Start, end and middle with the slice pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read each arm as a sentence. [var first, .., var last] means "at least two elements; call the first one first and the last one last; ignore everything between". Two details:

  • [var first, .., var last] needs at least two elements, because it names two distinct positions. A one-element array is handled by the earlier [var only] arm.
  • The switch expression is exhaustive here: every array has 0, 1 or 2 or more elements, and the arms cover those lengths. The compiler checks length reasoning like this for you, which is why there is no _ fallback.

Capturing slices

You can give the slice itself a name by putting a pattern after ... Writing .. var rest (or any pattern, such as .. [1, 2] or .. { Length: > 2 }) captures the matched middle part as a new array, list or span, depending on the input type.

C# Capturing the rest of a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Sum is the textbook recursive definition over lists: the sum of an empty list is zero and the sum of a non-empty list is its head plus the sum of the tail. It reads beautifully but does real work: capturing a slice of an array creates a new array, copying the elements. So Sum copies the tail at every step and takes quadratic time. Use a loop or LINQ's Sum() in real code; the recursive version is for learning and for short inputs (see recursion in C# for the stack depth limits too).

The copy happens only when you capture the slice into a variable. A bare .. in the pattern (without a name) is free: the compiler just checks the length and tests the elements at fixed positions. Pattern types that support slicing without copying, such as ReadOnlySpan<T>, return a span view instead of a new array.

List patterns on strings and spans

A string is indexable and has a Length, so list patterns work on characters directly. This is a compact way to test prefixes, suffixes and formats.

C# List patterns on strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For strings, text is ['#', ..] is equivalent to text.StartsWith('#') and [.., ';'] to EndsWith(';'). Prefer the pattern when it appears alongside other patterns in a switch; prefer the method when it stands alone, because it reads more plainly. Note that list patterns work on UTF-16 code units, the char values; a character outside the basic plane (many emoji) is two elements. See Unicode and encoding.

Practical use: parsing commands

Many programs read lines such as add milk 2 or remove eggs. Splitting the line into words and matching the array of words is a natural fit for list patterns.

C# A small command interpreter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Compare this with the same logic written with words.Length == 2 && words[0] == "add". The patterns state the command shape and the argument names in one place, and ["add", ..] gives a natural catch-all usage message for "add" with the wrong number of arguments. The order of arms matters: the two exact-shape add arms must come before the ["add", ..] arm.

Combining list, property and positional patterns

List patterns are ordinary patterns, so they nest inside others. You can match a record whose property holds a list, or a list of records.

C# Lists inside other patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This is how a tiny router can be built in a few lines. Real frameworks use dedicated route tables, which are faster and more flexible, but the pattern version is excellent for tests, tools and small programs.

Lists of objects

A list pattern's elements can be any pattern, including type and property patterns. That makes it possible to check a heterogeneous array in one expression.

C# Matching arrays of mixed objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Rules and limits to remember

  • One slice only. A list pattern may contain at most one ..; two would be ambiguous.
  • Length semantics. Without .. the pattern requires the exact length; with .. it requires at least the number of other elements.
  • Not for IEnumerable<T>. The input must be countable and indexable; enumerate to an array first, accepting the allocation.
  • Evaluation is by index. The compiler reads elements with the indexer and the length with Length/Count. A custom collection with an expensive indexer (a linked list, say) will be slow. Pattern matching does not make the access cheaper.
  • Slices allocate unless the type slices as a view. Arrays and List<T> copy; Span<T> and ReadOnlySpan<T> do not. A custom type can opt in by providing a Slice(int, int) method.
  • Order of arms matters as always, and the compiler flags an arm that an earlier one already covers.

When a list pattern becomes hard to read, you are probably encoding a grammar: consider a small parser, a regular expression (see regular expressions) or a switch over a parsed record instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which array matches the pattern [1, .., 9]?

    The pattern needs a first element 1 and a last element 9, with any number of elements (including none) between them. [1, 9] fits, [1] has no separate last element.
  2. 2. What does [var first, .. var rest] do for an array of five elements?

    The slice pattern can be followed by a pattern or a var designation. For arrays the captured slice is a new array holding the remaining elements.
  3. 3. Which type cannot be used directly with a list pattern?

    List patterns need a length (Length or Count) and an int indexer. IEnumerable<T> offers neither, so convert it with ToArray() or ToList() first.
  4. 4. How many slice patterns (..) may a single list pattern contain?

    Two slices would make it ambiguous which elements each one covers, so at most one .. is allowed in a list pattern.
  5. 5. Why is the recursive Sum([head, ..tail]) version slow for large arrays?

    Capturing a slice of an array allocates and copies the elements. Doing that at every recursion step makes the total work quadratic.

Summary

  • List patterns (C# 11) match sequences by shape: [1, 2, 3] for an exact match, _ for any element, var x to capture one.
  • The slice pattern .. stands for zero or more elements, may appear once, and makes the length test "at least" instead of "exactly".
  • .. var rest captures a slice; for arrays and lists this copies, for spans it is a free view.
  • Strings and spans work, which gives compact prefix, suffix and format tests; remember they operate on UTF-16 code units.
  • List patterns nest inside property, positional and type patterns, which is ideal for command parsing and simple routing.
  • The input must be countable and indexable; convert plain IEnumerable<T> first, and watch for copies in recursive code.

Next: Modeling with Records and Pattern Matching