.NET Development
List patterns in C#: positions and shape, not contains
A list pattern matches a sequence, such as an array, a list, a span or a string, against a list of patterns, one position at a time. Given int[] numbers = { 1, 2, 3 };, the expression numbers is [1, 2, 3] is true and numbers is [1, 2, 3, 4] is false. A list pattern describes the shape the data is expected to have: how many elements there are and what goes in each position. It works with is and with switch.
The slice .. matches zero or more elements. It appears at most once per pattern and lets a pattern look only at the start ([first, ..]), only at the end ([.., last]) or at both ends. With .. var rest, it also stores the elements it covers in a variable.
What it is for
It replaces chains of if statements that check Length and read loose indexes, like the ones that parse command-line arguments, the segments of a path or the fields of a line of text.
Why it exists
C# has had pattern matching since version 7.0, but until C# 10 there was no way to describe a sequence by its elements. The proposal was opened on May 7, 2020, and the feature shipped in C# 11, the language version .NET 7 uses by default, in November 2022. The official history of C# presents it as an extension of pattern matching, not as separate syntax. It also appears in the overview of what is new in C# 11.
A real-life example
A train inspector checks that the locomotive is at the front, that the last car is the caboose and how many cars there are in total. The inspector does not walk the train looking for the dining car. That is how a list pattern compares: positions and length, not whether a value is somewhere in the sequence.
Before and after
The repository parses the words of a to-do command: add <title>, done <id> and tag <id> <tag>..., with --help at the end to ask for help. The same logic is written twice: DescribeWithIfs, with if statements, lengths and indexes, and Describe, with a switch and list patterns. A test checks that both return the same text for 17 inputs. The whole file compiles in a .NET 10 console project (src/ListPatternsDemo/TodoCommand.cs):
namespace ListPatternsDemo;
/// <summary>
/// Turns the words of a small to-do command line into a description of what would run.
/// The same rules are written twice: with if statements and indexes, and with list patterns.
/// </summary>
public static class TodoCommand
{
public const string Usage = "Usage: todo add <title> | done <id> | tag <id> <tag>...";
/// <summary>Before: length checks and indexes, one if per rule.</summary>
public static string DescribeWithIfs(string[]? args)
{
if (args == null || args.Length == 0)
{
return Usage;
}
if (args[args.Length - 1] == "--help")
{
return Usage;
}
if (args.Length == 2 && args[0] == "add")
{
return $"Add task: {args[1]}";
}
if (args.Length == 2 && args[0] == "done")
{
return $"Complete task {args[1]}";
}
if (args.Length >= 3 && args[0] == "tag")
{
string[] tags = args[2..];
return $"Tag task {args[1]}: {string.Join(", ", tags)}";
}
return $"Unknown or incomplete command: {args[0]}";
}
/// <summary>After: one switch arm per rule, each arm states the shape it expects.</summary>
public static string Describe(string[]? args) => args switch
{
null or [] => Usage,
// Only the last word is compared: "--help" anywhere else is an ordinary word.
[.., "--help"] => Usage,
// Exactly two words: "add milk now" does not match this arm.
["add", var title] => $"Add task: {title}",
["done", var id] => $"Complete task {id}",
// The slice keeps every word after the id; the property pattern asks for at least one.
["tag", var id, .. { Length: > 0 } tags] => $"Tag task {id}: {string.Join(", ", tags)}",
// Any other non-empty input: only the first word is read.
[var command, ..] => $"Unknown or incomplete command: {command}",
};
/// <summary>
/// Counts the tags of a "tag" command. On an array, the slice is a new array with copied elements.
/// </summary>
public static int CountTags(string[] args) => args is ["tag", _, .. var tags] ? tags.Length : 0;
/// <summary>
/// The same count over a span: the slice is a view of the same memory, so nothing is copied.
/// </summary>
public static int CountTags(ReadOnlySpan<string> args) => args is ["tag", _, .. var tags] ? tags.Length : 0;
}
.. { Length: > 0 } tags puts a subpattern inside the slice to ask for at least one tag. The null or [] arm is needed because a list pattern does not match null, and no other arm accepts an empty list. Without that arm, the compiler warns with CS8509; if only the null part is missing, with CS8655. This project treats warnings as errors, so it does not build; in a project that only warns, the input left without an arm throws SwitchExpressionException.
Positions, not "contains"
[.., "--help"] looks only at the last element. With add --help it returns the help text; with add --help x it does not, and the input falls through to the last arm: "Unknown or incomplete command: add". In the same way, add milk now does not match ["add", var title], because without a slice the length is exact.
The order of the arms matters too: the first one that matches wins, which is why the help arm comes before the commands. If an earlier arm hides a later one, the compiler reports error CS8510. Constants are compared as string values, ordinally and case-sensitively: ADD, a fullwidth "a" or a leading space do not match "add". If those variants must be accepted, the input is normalized before the switch.
Contains.Which types it accepts, and since which version
The specification asks for a type that is countable, with a Length or Count property of type int, and indexable, with an indexer that takes an Index or an int. Storing the slice in a variable also needs an indexer that takes a Range or a Slice(int, int) method. Checked with SDK 10.0.401:
| Type | List pattern | Slice with a variable |
|---|---|---|
Array, string | Yes | Yes, as a copy |
List<T> | Yes | Yes, as a copy (Slice creates a new list) |
Span<T> | Yes | Yes, as a view |
IReadOnlyList<T> | Yes | No (CS1503) |
IEnumerable<T> | No (CS8985) | No |
Multidimensional arrays are not supported either. Without extension members, IEnumerable<T> does not work in C# 14 or in C# 15. The language team discussed it in 2021: a lazy sequence can be infinite, and counting it would hang the program, or it can be expensive, like a database query that should not run more than once. It still decided to keep designing that support, which did not ship with C# 11 and is still missing. To apply a list pattern to a LINQ query, the direct way is to materialize it first, which reads all of it.
The minimum version is C# 11: with LangVersion 10, the compiler reports CS8936. .NET 10 uses C# 14, and C# 15, which comes with .NET 11, adds extension indexers: an extension block could already supply the Count, and now it can supply the indexer too, so a type that has neither accepts list patterns. That block can also be written for IEnumerable<T>, with Count() and ElementAt(), and then it compiles: each pattern enumerates the sequence several times, and an endless sequence hangs the program.
What a slice with a variable costs
On an array, .. var tags creates a new array with the elements copied: the compiler uses RuntimeHelpers.GetSubArray, and Substring on a string. On a span, the slice is a view of the same memory. With 1,000,000 tags, the same pattern allocated 8,000,024 bytes over an array and 0 bytes over a ReadOnlySpan<string>. Those are the two CountTags methods in the file above, run on runtime 10.0.12. Memory was measured, not speed.
.. var. For large sequences, passing a Span<T> instead of the array, the string or the List<T> avoids it.What the code does not cover
The switch decides the shape of the input, not whether its values make sense.
nullelements inside the array:varaccepts them, and the input[null]returns "Unknown or incomplete command: " with an empty value.- The meaning of the values:
done abcis accepted as an id, andadd ""ortag 7 ""are accepted with an empty value ({ Length: > 0 }counts elements, it does not check their text). Validating values is a separate step, after theswitch. - The output: the returned text repeats the title, the id, the tags or the first word as they arrived. If that text goes into an HTML page or a log, it is encoded at that point.
Conclusion
List patterns fit when position carries meaning, as in arguments, paths or fields, and they do not replace Contains when membership is what matters.
References
- NippysoftLabs: csharp-list-patterns (github.com)
- Patterns - Pattern matching using the is and switch expressions (list patterns) (learn.microsoft.com)
- List patterns (C# 11 feature specification) (github.com)
- The history of C# (learn.microsoft.com)
- Language versioning (learn.microsoft.com)
- What's new in C# 15 (learn.microsoft.com)
- C# Language Design Meeting for Feb 3rd, 2021 (github.com)
- Proposal: list pattern (github.com)
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment