In C# 12, what does `[..groundRow, ..wallRow, 0]` create when it is assigned to an `int[]`, a `List<int>` and an `IEnumerable<int>`?
answer
- the target decides the type
- no natural type for var
- spread enumerates right away
- interfaces get compiler-chosen types
basics
~20 sA new collection of the target's type holding groundRow's elements, then wallRow's, then 0: a new int[], a new List<int> sized to fit, or a read-only collection the compiler synthesizes for IEnumerable<int>. The spread copies elements immediately.
solid answer
~40 sA collection expression (C# 12) has no type of its own; the target type decides what is built, which is why `var tiles = [1, 2];` fails with CS9176. Each spread element `..e` enumerates `e` and adds its elements in order, at the moment the expression runs. For `int[]` the result is a new array of exactly the combined length; for `List<int>` a new list whose capacity equals the element count; for `IEnumerable<int>`, `IReadOnlyCollection<int>` or `IReadOnlyList<int>` a compiler-synthesized read-only type; for `ICollection<int>` or `IList<int>` a `List<int>`. Nothing stays linked to `groundRow` or `wallRow`. `[]` assigned to an array reuses `Array.Empty<T>()`, but builds a new list each time for `List<T>`. A collection expression is never a constant, so `const int[] c = [1];` fails with CS0133.
code
csharp · 20 linesint[] groundRow = [1, 1, 1];
int[] wallRow = [2, 2];
int[] tiles = [..groundRow, ..wallRow, 0];
List<int> editable = [..groundRow, ..wallRow, 0];
IEnumerable<int> readOnly = [..groundRow, ..wallRow, 0];
IList<int> mutable = [..groundRow, ..wallRow, 0];
Console.WriteLine($"{string.Join(",", tiles)} Length={tiles.Length}");
Console.WriteLine($"List<int> Count={editable.Count} Capacity={editable.Capacity}");
Console.WriteLine(readOnly.GetType()); // a compiler-synthesized read-only type
Console.WriteLine(mutable.GetType()); // List<int>
int[] empty1 = [], empty2 = [];
Console.WriteLine(ReferenceEquals(empty1, empty2)); // True: both are Array.Empty<int>()
int pulled = 0;
IEnumerable<int> Load() { for (int i = 0; i < 3; i++) { pulled++; yield return i; } }
IEnumerable<int> loaded = [..Load()];
Console.WriteLine($"enumerated already: {pulled}"); // 3, before anything reads 'loaded'go deeper
Write arrays and lists with brackets and use ..source to include another collection. Know that the type comes from the variable you assign to.
Explain target typing and CS9176, what each target builds, that spread enumerates and copies at once, and why [] for an array is Array.Empty<T>() but a new list for List<T>.
Notice when a spread over a query or iterator runs work earlier than the old code did, and when an interface target hides a read-only synthesized type that a caller later casts and tries to modify.
Adopting collection expressions across a codebase is mostly a style decision with an analyzer to enforce it; the point to settle is whether public members return interface types built this way, since callers cannot modify them.
## The syntax A **collection expression**, added in C# 12, is a list of elements between square brackets: `[1, 2, 3]`. Compiling one with `LangVersion` 11 fails with **CS9058** ("Feature 'collection expressions' is not available in C# 11.0"). Each element is either an expression or a **spread element** written `..e`, which inserts every element of `e`: ```csharp int[] groundRow = [1, 1, 1]; int[] wallRow = [2, 2]; int[] tiles = [..groundRow, ..wallRow, 0]; // 1,1,1,2,2,0 ``` ## The target decides what is built A collection expression has **no natural type**. The compiler looks at the type it is converted to, called the **target type**, and builds that. With no target there is nothing to build: `var tiles = [1, 2, 3];` fails with **CS9176** ("There is no target type for the collection expression"). | Target type | What the SDK 10.0.401 compiler builds | |---|---| | `int[]` | a new array of exactly the element count | | `List<int>` | a new list whose `Capacity` equals the element count | | `Span<int>`, `ReadOnlySpan<int>` | a span whose storage might be stack allocated | | `IEnumerable<int>`, `IReadOnlyCollection<int>`, `IReadOnlyList<int>` | a compiler-synthesized read-only collection | | `ICollection<int>`, `IList<int>` | a `List<int>` | | a type with a collection initializer or `[CollectionBuilder]` | that type, built through `Add` or the builder method | The synthesized type for the read-only interfaces is a compiler detail: in a test run its name printed as `` <>z__ReadOnlyArray`1[System.Int32] ``, and casting it to `ICollection<int>` and calling `Add` threw `NotSupportedException`. Code should rely on the interface, not on the class behind it. ## What the spread element does - **It enumerates the source.** The operand of `..` must be something `foreach` can walk over: an array, a list, a span, a LINQ query, an iterator. - **It runs now.** The docs state that a collection expression always creates a collection holding all of its elements, even when the target is `IEnumerable<T>`. In the example, the iterator behind `[..Load()]` had produced all three values before anything read the result. That differs from a LINQ query, which waits until enumeration. - **It copies.** The new collection holds the element values (or references, for class elements). Changing `groundRow[0]` later does not change `tiles`. - **Order is preserved.** Elements appear in the order written, spreads included. - **When the counts are known**, as with arrays and lists, the compiler allocates the result once at its final size. ## Empty and constant cases 1. `[]` assigned to an array, or to a read-only interface, can be **`Array.Empty<T>()`**; in a test run two `int[] x = [];` locals were the same instance. Assigned to `List<T>`, `[]` creates a new empty list every time, because a list may be modified. 2. A collection expression is not a **compile-time constant**: `const int[] c = [1];` fails with **CS0133**, and it cannot be an optional parameter's default value. 3. A multidimensional array such as `int[,]` cannot be the target (**CS9174**), while a jagged `int[][]` can: `[[1, 1], [2], []]`. ## Using it in the level editor Collection expressions make the editor's construction code read like the data: - **Building a row**: `int[] border = [..wall, ..floor, ..wall];` instead of allocating an array and copying three times by hand. - **Starting a list**: `List<Entity> placed = [..prefabs, player];` gives a list sized for its first contents that can grow afterwards. - **Returning a read-only view of fresh data**: `IReadOnlyList<int> Snapshot() => [..current];` returns a new collection whose type the caller cannot add to. - **Avoiding surprises**: spreading a query, as in `[..entities.Where(e => e.Visible)]`, runs the query once, there and then; if you wanted a lazy sequence, return the query instead. The usual mistakes are expecting `var` to work, expecting a spread over a query to stay lazy, and assuming that an `IEnumerable<int>` target gives you a `List<int>` you can cast back and modify. One more limit: in C# 14 a collection expression cannot pass a capacity or a comparer to the collection it builds. A `HashSet<string>` target is built with the default equality comparer, so a case-insensitive set still needs `new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ... }` or a constructor call wrapped around the expression; a `with(...)` element for such arguments exists only as a C# 15 preview feature.
- Why does a method overloaded for `int[]` and `IEnumerable<int>` pick the array overload when called with `Draw([1, 2, 3])`?Both conversions exist, so overload resolution compares them, and the language prefers a conversion to a non-interface type over one to an interface type. The array overload wins. Spans rank higher still: an overload taking `ReadOnlySpan<int>` beats both, because conversion to a ref struct type such as a span is preferred.
- Is `List<int> copy = [..source];` the same as `source.ToList()`?The result is the same kind of object, a new `List<int>` holding the same elements in the same order, and both enumerate `source` immediately. The collection expression is target-typed, so the same syntax can produce an array or a span instead, and the compiler chooses how to build it, sizing the list once when `source` has a known count.
- var x = [1, 2, 3] infers an int[].
- Spreading a LINQ query into an IEnumerable<T> keeps it lazy.
- An IEnumerable<int> target always gives you a List<int> underneath.
- The spread element keeps the new collection linked to its source.
- Collection expressions work with int[,] like any other array.