In a C# argument parser, how does the switch arm `["deploy", var env, .. var rest]` match argv, and what does rest hold?
answer
- fixed positions set a minimum
- zero or more in the middle
- one slice per list pattern
- slice type follows the input
basics
~20 sThe arm matches a non-null string[] of two or more elements starting with "deploy"; env binds index 1, and .. var rest binds the remaining elements as a new string[], empty when argv has exactly two.
solid answer
~40 sThe two fixed positions make the minimum length two, so the compiler tests `argv.Length >= 2`, then `argv[0] is "deploy"`, binds `argv[1]` to `env`, and binds the slice from index 2 to the end to `rest`. A slice pattern `..` matches **zero or more** elements and may appear at most once per list pattern; a second one is error CS8980. For an array input the captured slice is a new array of the same type, so `rest` is a `string[]` (an empty one when only two arguments were given, never null). Inside a switch expression arms are tried in order, so this arm must come before a catch-all like `[var command, ..]`; otherwise the compiler rejects it as already handled (CS8510).
code
csharp · 16 linesusing System;
Console.WriteLine(Route(new string[0]));
Console.WriteLine(Route(new[] { "deploy" }));
Console.WriteLine(Route(new[] { "deploy", "staging" }));
Console.WriteLine(Route(new[] { "deploy", "prod", "--force", "--verbose" }));
Console.WriteLine(Route(new[] { "rollback", "prod" }));
static string Route(string[] argv) => argv switch
{
[] => "usage: tool <command>",
["deploy"] => "deploy needs an environment",
["deploy", var env, .. var rest] =>
$"deploy to {env}, {rest.Length} option(s): {string.Join(' ', rest)}",
[var command, ..] => $"unknown command '{command}'",
};go deeper
Recall that .. matches zero or more elements and that var binds whatever sits at a position.
Explain how fixed positions set the minimum length, how positions after a slice count from the end, and why rest is an empty string[] rather than null.
Spot the review issues: a catch-all arm placed too early (CS8510), a missing [] arm (CS8509), and a captured slice copied on every call when only a count was needed.
Decide whether a hand-written list-pattern parser is enough for the tool's command line or whether the option grammar has grown past fixed positions.
## Anatomy of the arm ```csharp ["deploy", var env, .. var rest] => ... ``` This is a **list pattern** (C# 11) with three parts: - `"deploy"`: a **constant pattern** for the element at index 0. - `var env`: a **var pattern** that matches any value at index 1 and binds it to a new local `env`. - `.. var rest`: a **slice pattern**. `..` matches zero or more consecutive elements; the `var rest` after it is a nested pattern applied to that run of elements as a whole, binding it to `rest`. ## How the compiler counts Every non-slice position counts toward a **minimum length**; the slice absorbs whatever is left. Positions after a slice are addressed from the end. Following the lowering in the C# 11 design document, the arm becomes roughly: 1. `argv` is not null. 2. `argv.Length >= 2` (two fixed positions). 3. `argv[0] is "deploy"`. 4. `argv[1] is var env` (always succeeds once the length passed). 5. the slice from index 2 to the end `is var rest`. | Pattern | Minimum length | What each part reads | |---|---|---| | `["deploy", var env, .. var rest]` | 2 | index 0, index 1, slice from 2 to the end | | `["deploy", .., var last]` | 2 | index 0, the last element | | `[.. var init, "--dry-run"]` | 1 | slice of all but the last, the last element | | `[..]` | 0 | nothing; no length test is emitted | So `{ "deploy", "staging" }` matches with an empty `rest`, and `{ "deploy" }` does not match this arm at all. ## What `rest` is The type of a captured slice is the return type of whatever member the compiler slices with. For arrays the compiler calls `RuntimeHelpers.GetSubArray`, which returns a new array of the same type, so `rest` is a `string[]`. For a `string` input the slice is a `string`, for a `Span<T>` a `Span<T>`, for a `List<T>` a `List<T>` (through `List<T>.Slice(int, int)`). - An empty slice is still an array, never null; for a plain `string[]` (not a covariant array stored as another element type), `GetSubArray` returns the cached `Array.Empty<string>()`. - A non-empty slice of an array is a **copy**: writing `rest[0] = "x"` does not change `argv[2]`. ## Slices before fixed positions When the slice comes first, the fixed positions after it are read **from the end**. `[.. var init, "--dry-run"]` tests `Length >= 1`, checks that the last element is `"--dry-run"`, and binds every element before it to `init`. For `{ "deploy", "prod", "--dry-run" }`, `init` is the two-element array `{ "deploy", "prod" }`. This is how a parser handles a trailing flag without knowing how many arguments precede it. A slice in the middle, as in `[var first, .., var last]`, reads one element from each end and needs at least two elements, because `first` and `last` must be different positions. ## Rules on the slice pattern - **At most one slice** per list pattern. `[.., "--force", ..]` is error CS8980: "Slice patterns may only be used once and directly inside a list pattern." - The slice must sit **directly** inside a list pattern; `..` on its own is not a pattern. - It can appear at the **start, middle or end**: `[.., "--force"]` anchors the last element. - Any pattern may follow `..`, not just `var`: `.. { Length: > 0 } opts` binds the options only when there is at least one. - A bare `..` with nothing after it only relaxes the length test; it creates no slice. ## Putting it in a switch expression The full parser routes four shapes: ```csharp static string Route(string[] argv) => argv switch { [] => "usage: tool <command>", ["deploy"] => "deploy needs an environment", ["deploy", var env, .. var rest] => $"deploy to {env} ...", [var command, ..] => $"unknown command '{command}'", }; ``` Two compiler checks apply, both owned in detail by the material on switch expressions: 1. **Arm order.** Arms are tried top to bottom. If `[var command, ..]` came first it would already cover every non-empty array, and the deploy arm would be rejected with CS8510, "The pattern is unreachable." 2. **Exhaustiveness.** Without the `[]` arm the compiler warns CS8509 and, on the .NET SDK 10.0.401, names `'{ Length: 0 }'` as the uncovered case. The arms together read like a grammar for the command line: each describes one accepted shape, and the compiler checks that the shapes do not shadow each other.
- What does the compiler report for `["deploy", .., var env, ..]`?Error CS8980: "Slice patterns may only be used once and directly inside a list pattern." C# allows one slice per list pattern, so express the intent with a single slice plus fixed positions, or a pattern applied to that slice.
- How do you make the deploy arm require at least one option after the environment?Put a pattern after the slice: `["deploy", var env, .. { Length: > 0 } opts]`. The property pattern applies to the slice, so the arm matches only when the slice has one element or more, and `opts` binds it as a `string[]`.
- Why does the compiler reject the deploy arm if `[var command, ..]` is written above it?Switch expression arms are tested in order, and `[var command, ..]` already matches every non-null array with one element or more, which includes every array the deploy arm could match. The compiler reports CS8510, "The pattern is unreachable"; move the specific arm above the catch-all.
- The slice .. must always be the last element of a list pattern.
- rest is null when argv contains exactly two elements.
- You can write .. twice to skip two separate runs of elements.
- rest is a live view over argv, so writing to it changes argv.
- ["deploy", var env, .. var rest] needs at least three elements.