skip to content

In C#, how do you nest patterns inside a list pattern to recognise CSV comment, header and data rows held in a string[]?

level: middleimportance: should knowfreq 40%

answer

  1. any pattern at any position
  2. a string is a list of char
  3. patterns after the slice too
  4. span against a constant string

basics

~20 s

Each position of a C# list pattern takes any pattern: in a CSV row check, [['#', ..], ..] means the first cell starts with '#', and [_, .., { Length: 0 }] means at least two cells with an empty last one.

solid answer

~40 s

A list pattern (C# 11) applies a full pattern at each position, so you can nest constant, `var`, discard, property, relational and other list patterns. A `string` is itself countable and indexable with `char` elements, so `[['#', ..], ..]` is an outer pattern over the row whose first element is matched by an inner list pattern over that cell's characters. The inner elements must be `char` constants: `["#", ..]` against a string is CS0029. Property patterns such as `{ Length: 0 }` test one cell, and a pattern after `..` tests the slice as a whole. A `ReadOnlySpan<char>` can be matched character by character and, since C# 11, against a constant string such as `"id"`.

code

csharp · 17 lines
csharp
using System;

Console.WriteLine(Check(new[] { "#generated", "2026-10-10" }));
Console.WriteLine(Check(new[] { "id", "name", "updated_at" }));
Console.WriteLine(Check(new[] { "42", "Ada", "" }));
Console.WriteLine(Check(new[] { "42", "Ada", "2026-10-01" }));
Console.WriteLine(Check(new[] { "42" }));
Console.WriteLine("\"Ada\"" is ['"', .., '"']);

static string Check(string[] cells) => cells switch
{
    [['#', ..], ..] => "comment row",
    ["id", .., "updated_at"] => "header row",
    [_, .., { Length: 0 }] => "data row with an empty last cell",
    [{ Length: > 0 }, _, ..] => "data row",
    _ => "too few cells",
};

go deeper

for a junior

Recall that each position in a list pattern can hold any pattern, and that a string's elements are chars.

for a middle

Explain how a nested list pattern matches one element that is itself a sequence, why '#' and not "#" goes inside it, and how a pattern after .. tests the slice.

for a senior

Review a pattern-based row classifier for arm order, null cells and hidden slice copies, and move hot paths to ReadOnlySpan<char> with constant string patterns.

for a principal

Decide when a set of nested list patterns is still the clearest specification of a file format and when a dedicated parser should own it instead.

## Any pattern at any position The grammar of a **list pattern** (C# 11) is a bracketed, comma-separated list of patterns, plus at most one slice. Nothing restricts which patterns can appear, so each position can hold: - a **constant pattern**: `"id"`, `'#'`, `0`; - a **var pattern** or **discard**: `var cell`, `_`; - a **property pattern**: `{ Length: 0 }`; - a **relational pattern** on a numeric element: `> 0`, `>= 10 and < 50`; - **another list pattern**, when the element is itself a sequence. The rules of property, relational and logical patterns themselves belong to the material on those patterns; the point here is how they combine inside brackets. ## A string is a list of `char` `string` has `Length` and an `int` indexer returning `char`, so it is a valid list-pattern input whose elements are characters. | Pattern on a `string` | Meaning | |---|---| | `['#', ..]` | starts with `#` | | `['"', .., '"']` | at least two characters, quoted at both ends | | `[_, _, _]` | exactly three characters | | `["#", ..]` | does not compile: CS0029, "Cannot implicitly convert type 'string' to 'char'" | The last row is the common slip: inside a list pattern on a string, each position is one `char`, so the constant must be a `char` literal. ## Nesting in the CSV checker A CSV reader hands each row over as `string[] cells`. One switch expression classifies it: ```csharp static string Check(string[] cells) => cells switch { [['#', ..], ..] => "comment row", ["id", .., "updated_at"] => "header row", [_, .., { Length: 0 }] => "data row with an empty last cell", [{ Length: > 0 }, _, ..] => "data row", _ => "too few cells", }; ``` Reading the arms: 1. `[['#', ..], ..]`: the row has one cell or more, and the **first cell** (a `string`) matches `['#', ..]`, so it starts with `#`. 2. `["id", .., "updated_at"]`: at least two cells, the first exactly `"id"`, the last exactly `"updated_at"`. 3. `[_, .., { Length: 0 }]`: at least two cells and the last one is empty. The property pattern also rejects a null cell. 4. `[{ Length: > 0 }, _, ..]`: at least two cells and a non-empty first cell. 5. `_`: everything else, including a one-cell row. Arms are tried in order, so a comment row such as `{ "#note", "" }` is reported by arm 1 and never reaches arm 3, even though its last cell is empty. ## Patterns on the slice The pattern after `..` applies to the slice as a whole, which on a `string[]` is a `string[]`: - `[_, .. { Length: > 1 }]` requires at least two cells after the first. - `[_, .. [_, _]]` requires exactly two cells after the first; the nested list pattern is matched against the slice. - `[1, .. [2, 3]]` on an `int[]` matches `{ 1, 2, 3 }`. A captured slice costs an allocation on arrays; that trade-off is its own question. ## Binding while testing A nested pattern can also bind. A property or list pattern accepts a designation after it, and logical patterns combine tests at one position: - `[{ Length: > 0 } id, .., var last]` binds `id` only when the first cell is non-empty, and binds `last` unconditionally. - `[not "", .., ""]` requires a non-empty first cell and an empty last one. - `[['#', .. var comment], ..]` binds the text after `#` as a `string`. Binding inside the pattern keeps the test and the variable together, so an arm body never reads a cell the pattern did not check. ## Spans of `char` When the parser works on `ReadOnlySpan<char>` to avoid allocating strings, two kinds of pattern apply: - **List patterns**, element by element: `cell is ['#', ..]`. - **Constant string patterns**: since C# 11, a `Span<char>` or `ReadOnlySpan<char>` can be matched against a constant string, so `cell is "id"` compares the characters without creating a string. On C# 10 that line is CS8936. ## Things that surprise people - The order in which a list pattern tests its positions is **unspecified**, and a failed match may skip some tests, so a nested pattern must not depend on side effects. - A nested list pattern on a null cell does not match: like any list pattern it includes a null test. - The outer `..` in `[['#', ..], ..]` is what lets the row have more than one cell; without it, `[['#', ..]]` matches only one-cell rows.

  • Why does `line is ["#", ..]` fail to compile when `line` is a string?
    A list pattern over a `string` matches its `char` elements, so each position's constant must convert to `char`. `"#"` is a string constant, and the SDK reports CS0029, "Cannot implicitly convert type 'string' to 'char'". Write `['#', ..]` instead.
  • How do you test a `ReadOnlySpan<char>` cell for the value "id" without allocating a string?
    Use a constant pattern: `cell is "id"`. Since C# 11, `Span<char>` and `ReadOnlySpan<char>` can be matched against constant strings, which compares characters in place and also works as a switch arm. Compiling with LangVersion 10 reports CS8936 for that line.

  • A string cannot be matched with a list pattern; only arrays and lists can.
  • Only constants and var are allowed inside a list pattern.
  • On a string, ["#", ..] checks that it starts with "#".
  • A list pattern always tests its positions left to right, so side effects are safe.
  • Matching a ReadOnlySpan<char> against "id" needs a ToString() call first.