In C#, why does `args is ["--help"]` return false for an empty array while `args[0] == "--help"` throws?
answer
- count before contents
- no slice means exact length
- indexer has no guard
- the empty pattern []
basics
~20 sA C# list pattern without a slice tests the element count first, so ["--help"] needs exactly one element and an empty array simply fails the match. Indexing args[0] reads an element with no length check and throws IndexOutOfRangeException.
solid answer
~30 sA list pattern (C# 11) such as `args is ["--help"]` behaves like a null check, then `args.Length is 1`, then `args[0] is "--help"`; the length test comes before any element is read. With no `..` slice the count must be exact, so the pattern rejects an empty array and also `["--help", "--verbose"]`. The expression `args[0] == "--help"` has no guard: on an empty array the array indexer throws `IndexOutOfRangeException` before the comparison runs. The empty list pattern `[]` matches only a zero-length input, and `["--help", ..]` relaxes the count to "one or more".
code
csharp · 18 linesusing System;
string[][] inputs = { new string[0], new[] { "--help" }, new[] { "--help", "--verbose" } };
foreach (string[] argv in inputs)
{
Console.WriteLine($"Length {argv.Length}: is [\"--help\"] -> {argv is ["--help"]}");
}
string[] empty = new string[0];
try
{
Console.WriteLine(empty[0] == "--help");
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"empty[0] threw {ex.GetType().Name}");
}go deeper
Know that a list pattern with no .. checks the element count exactly, and that it returns false instead of throwing when the array is empty or too short.
Explain the order the compiler emits: null test, then Length, then the element tests, and how adding .. turns the exact count into a minimum.
Show where the pattern removes a whole class of IndexOutOfRangeException bugs in argument and message parsing, and when a Length property pattern reads more clearly.
Judge whether list patterns belong in the team's parsing code at all; they help fixed-position formats and hide intent when the logic really scans every element.
## What a list pattern tests A **list pattern**, added in C# 11, matches a sequence by its shape: how many elements it has and what sits at each position. It is written in square brackets, one nested pattern per position: ```csharp if (args is ["--help"]) PrintUsage(); ``` Here `args` is the **pattern input** (a `string[]`), and `"--help"` is a **constant pattern** applied to the element at index 0. The C# 11 design document lowers `expr is [1, 2, 3]` to a length test followed by one element test per position, which for this example reads as: 1. `args` is not null (a list pattern on a reference type always includes this test). 2. `args.Length is 1`. 3. `args[0] is "--help"`. The order in which the element tests run is left unspecified, but every element test depends on the length test having passed, so the generated code never reads an index that does not exist. ## The exact-count rule A list pattern **without a slice** (`..`) demands an exact count: one nested pattern per element, no more, no fewer. | Pattern | Lengths it accepts | Notes | |---|---|---| | `[]` | exactly 0 | the **empty list pattern** | | `["--help"]` | exactly 1 | element 0 must equal `"--help"` | | `["--help", _]` | exactly 2 | `_` is a discard: any value | | `["--help", ..]` | 1 or more | `..` is a **slice pattern**: zero or more extra elements | | `[..]` | any non-null input | no length test is emitted | So `["--help"]` is false for `new string[0]`, true for `{ "--help" }` and false for `{ "--help", "--verbose" }`. A command-line tool that wants "first argument is --help, ignore the rest" writes `["--help", ..]`. ## Why the indexer throws and the pattern does not `args[0] == "--help"` is two separate operations: an **array element access**, then a string comparison. Array element access in C# is bounds-checked at run time, and an index outside `0..Length-1` throws `System.IndexOutOfRangeException`. Nothing in that expression looks at `Length` first, so an empty array (a program started with no arguments) crashes the program unless the code adds its own guard: ```csharp if (args.Length > 0 && args[0] == "--help") PrintUsage(); ``` The list pattern folds that guard into the pattern itself. Because the compiler emits the length test before any element access, the pattern can only evaluate to `true` or `false`; it never throws for a short or empty array. ## Null input - `args is ["--help"]` is `false` when `args` is null: the list pattern's built-in null test fails. - `args is []` is also `false` for null. "Empty" and "missing" stay different answers. - `args[0]` on a null array throws `NullReferenceException`, a second failure mode the pattern avoids. ## When a list pattern is the right tool - Use it when **fixed positions have meaning**: a command name at index 0, an option at the end. - Use a property pattern such as `args is { Length: 0 }` when only the count matters; the C# documentation notes that it states that intent more directly. - Use a loop or LINQ when the decision needs every element, such as "any argument starts with --". ## Release and review notes List patterns arrived in **C# 11**, which shipped with the .NET 7 SDK, so they are part of the C# 12 baseline of .NET 8 and every later release; compiling the same line with `LangVersion` 10 reports CS8936, "Feature 'list pattern' is not available in C# 10.0." In code review, the pattern form is worth suggesting wherever a hand-written guard appears: - `args.Length > 0 && args[0] == "--help"` becomes `args is ["--help", ..]`. - `args.Length == 1 && args[0] == "--help"` becomes `args is ["--help"]`. - `args != null && args.Length == 0` becomes `args is []`. Each rewrite keeps the guard and the test in one expression, so a later edit cannot drop the length check while keeping the index. ## Common misreadings - Reading `["--help"]` as "starts with --help". It means "is exactly one element, and that element is --help". - Expecting `[]` to match null. It does not; a list pattern never matches a null reference. - Assuming list patterns are for arrays only. They also work on `List<T>`, `string` (element type `char`) and spans, as long as the compile-time type has a `Length` or `Count` and an indexer.
- What does `args is ["--help", ..]` accept that `["--help"]` rejects?The slice pattern `..` matches zero or more remaining elements, so `["--help", ..]` accepts any non-null array of length one or more whose first element is `"--help"`, including `{ "--help", "--verbose" }`. The exact pattern `["--help"]` accepts only the one-element array.
- What do `args is []` and `args is { Length: 0 }` return when `args` is null?Both return `false`. A list pattern and a property pattern each include a non-null test on a reference-type input, so a null array matches neither. Code that must treat "no array" and "empty array" alike tests `args is null or []`.
- A list pattern reads element 0 first, so an empty array makes it throw.
- ["--help"] matches any array whose first element is --help.
- args is [] is true when args is null.
- List patterns only work on arrays, not on lists or strings.
- A list pattern loops over every element to compare the array.