In C#, why does `rows is [var first, ..]` fail to compile when rows is an IEnumerable<string>, and what must a type provide?
answer
- decided by the declared type
- countable plus indexable
- CS8985 names Length or Count
- capturing needs a Range indexer or Slice
basics
~20 sList patterns need a countable, indexable compile-time type: an accessible Length or Count property and an indexer taking Index or int. IEnumerable<string> has neither, so the compiler reports CS8985. Capturing a slice also needs a Range indexer or a Slice(int, int) method.
solid answer
~40 sThe compiler resolves a list pattern against the input's **declared** type, because it emits calls to the count and the indexer directly. A type is *countable* with an accessible `Length` or `Count` property and *indexable* with an indexer taking `Index` or a single `int`. `IEnumerable<string>` offers enumeration only, so `rows is [var first, ..]` fails with CS8985, "No suitable 'Length' or 'Count' property was found", even when the object is a `List<string>`. A bare `..` needs nothing more, but `.. var rest` also needs a `this[Range]` indexer or a `Slice(int, int)` method; `IList<T>` lacks both, which the SDK 10.0.401 reports as CS1503. Fix an enumerable input with a type pattern (`rows is IList<string> and [var first, ..]`) or materialise it first.
code
csharp · 19 linesusing System;
using System.Collections.Generic;
var row = new CsvRow("id", "name", "email");
Console.WriteLine(row is ["id", .., "email"]); // needs Count + this[int]
if (row is [_, .. var tail]) // also needs Slice(int, int)
Console.WriteLine($"{tail.GetType().Name} with {tail.Count} cell(s)");
IEnumerable<string> cells = new List<string> { "id", "name" };
Console.WriteLine(cells is IList<string> and [var first, ..] ? first : "not a list");
sealed class CsvRow
{
private readonly string[] _cells;
public CsvRow(params string[] cells) => _cells = cells;
public int Count => _cells.Length;
public string this[int index] => _cells[index];
public CsvRow Slice(int start, int length) => new(_cells[start..(start + length)]);
}go deeper
Recall that list patterns need Length or Count and an indexer, which is why arrays, lists and strings work and a plain IEnumerable<T> does not.
Explain that the check uses the declared type, and that capturing a slice adds a third requirement: a Range indexer or Slice(int, int).
Diagnose CS8985 and the less obvious CS1503 on a Range argument in review, and pick the fix: a type pattern to IList<T>, a materialised copy, or a better parameter type.
Decide whether shared collection types in a library should expose Count, an indexer and Slice so callers can pattern-match them, and what that promises about their behaviour.
## Countable and indexable A list pattern (C# 11) does not enumerate. The compiler turns it into a length test and indexed reads, so the input type must supply those members at compile time. The C# 11 design document names two properties: - **Countable**: an accessible `Length` or `Count` property returning `int`. - **Indexable**: an accessible indexer that takes `System.Index`, or otherwise one with a single `int` parameter. If both exist, the `Index` one is preferred. Arrays, `string`, `List<T>`, `IList<T>`, `IReadOnlyList<T>`, `Span<T>` and `ReadOnlySpan<T>` all qualify. So does your own type, without implementing any interface: ```csharp sealed class CsvRow { public int Count => ...; public string this[int index] => ...; } ``` ## The decision is static Eligibility comes from the **declared** type of the expression, not the object at run time. `IEnumerable<string> rows = new List<string>()` hides `Count` and the indexer, so the SDK 10.0.401 reports: - CS8985: "List patterns may not be used for a value of type 'IEnumerable<string>'. No suitable 'Length' or 'Count' property was found." - CS0021: "Cannot apply indexing with [] to an expression of type 'IEnumerable<string>'." The C# documentation states the reason: the compiler must resolve the required members before the program runs. ## Why the compiler does not enumerate A list pattern promises cheap, positional access: `[var first, .., var last]` reads two elements no matter how long the input is. Enumerating an `IEnumerable<T>` to reach the last element would mean walking the whole sequence, possibly running a database query or an iterator twice, and buffering it to support slices. The language design avoids that hidden cost by requiring members that give the count and any element directly. The documentation adds the practical rule: when the decision really needs to look at an arbitrary number of elements, use a loop or LINQ instead of a pattern. ## Capturing a slice needs one more member A slice pattern with a subpattern (`.. var rest`, `.. { Length: > 0 }`) also needs the type to be **sliceable**: a `this[Range]` indexer or, failing that, a `Slice(int start, int length)` method. A bare `..` only shifts the length test and needs nothing extra. | Declared input type | `[a, .., b]` | `.. var rest` | Type of `rest` | |---|---|---|---| | `T[]` | compiles | compiles | `T[]` (via `RuntimeHelpers.GetSubArray`) | | `string` | compiles, elements are `char` | compiles | `string` (via `Substring`) | | `Span<T>`, `ReadOnlySpan<T>` | compiles | compiles | the same span type | | `List<T>` | compiles | compiles | `List<T>` (via `List<T>.Slice`) | | `IList<T>`, `IReadOnlyList<T>` | compiles | CS1503 | no slicing member | | `IEnumerable<T>` | CS8985 | CS8985 | not countable | | `int[,]` | CS0022 | CS0022 | multi-dimensional arrays are not supported | For `IList<T>`, the compiler falls back to the `int` indexer for the slice and reports CS1503, "Argument 1: cannot convert from 'System.Range' to 'int'". That message points at the indexer, not at the pattern, which is why it confuses people in review. ## Custom types To make your own collection fully usable: 1. Expose `Count` (or `Length`) and `this[int]`; list patterns without a captured slice now compile. 2. Add `Slice(int start, int length)` returning a type that can itself be matched; `.. var rest` now compiles and `rest` has that return type. 3. Keep the members well-behaved. The design document lets the compiler assume a non-negative count and a slice that is never null and is a proper sub-slice; if they break those assumptions, the result of the match is undefined. ## Fixing an enumerable input - **Type pattern first**: `rows is IList<string> and [var first, ..]` narrows the input, then applies the list pattern, and allocates nothing. It is false whenever the object does not implement `IList<string>`. - **Materialise**: `rows.ToArray() is [var first, ..]` always works but copies the sequence and enumerates it fully. - **Change the declared type** of the parameter to `IReadOnlyList<string>` when callers always pass indexable collections. - **Do not reach for a list pattern** when the logic really scans the sequence; `rows.FirstOrDefault()` or a loop says that better.
- Your collection type has `Count` and `this[int]` but no `Slice`. Which list patterns still compile?Every list pattern that does not put a subpattern after `..`: exact patterns like `[1, 2]`, patterns with a bare slice like `[1, .., 3]`, and the empty pattern `[]`. Adding `.. var rest` or `.. { Count: > 0 }` needs a `this[Range]` indexer or `Slice(int, int)`; without one the SDK reports CS1503 on the `Range` argument.
- If a type has both `this[Index]` and `this[int]`, which one does a list pattern use?The C# 11 design document prefers the `Index` indexer when both are accessible, and likewise prefers `this[Range]` over a `Slice` method for slices. Most BCL collections expose only the `int` indexer and `Slice`, so the fallback is the common path.
- Any IEnumerable<T> works with list patterns because the compiler enumerates it.
- The compiler checks the runtime type, so a List<T> stored in an IEnumerable<T> variable matches.
- Every list pattern needs a Slice method, even one with a bare .. and no capture.
- Implementing IEnumerable<T> is what makes a custom type usable with list patterns.
- A two-dimensional array can be matched row by row with nested list patterns.