Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# 12 Collection Expressions: Syntax, Spread Operator, and Performance

How C# 12 collection expressions convert to arrays, spans, lists, and builder-backed types, and where the spread element and target-type rules decide performance.

~4 min readC#
#C##Collection Expressions#C# 12#Spread Operator
C# collection brackets combining arrays through spread elements into one collection

A collection expression is the bracket syntax that replaces both array initializers and collection initializers in C# 12: int[] a = [1, 2, 3];, List<string> names = ["a", "b"];, ReadOnlySpan<byte> header = [0x1F, 0x8B];. The same literal converts to arrays, spans, List<T>, immutable collections, types that opt in with a collection builder, and the IEnumerable<T> family, and the compiler picks the construction strategy from the target type. The spread element .. splices another sequence into the middle, so [.. prefix, item, .. suffix] replaces the Concat(...).ToArray() chains that allocate three intermediate objects.

One syntax, many target types

csharp
int[] numbers = [1, 2, 3, 4]; Span<byte> magic = [0x89, 0x50, 0x4E, 0x47]; List<string> tags = ["python", "java", "csharp"]; IEnumerable<Guid> ids = [Guid.NewGuid(), Guid.NewGuid()]; ImmutableArray<string> months = ["Jan", "Feb", "Mar"]; HashSet<int> seen = [1, 2, 2, 3]; // three elements, duplicates collapse

The element type does not have to be constant; any expression works, and the result is evaluated left to right:

csharp
string[] Create(string first, string last) => [first, "middle", last];

Three target families are supported. Arrays and spans are built directly. Types that expose a Create(ReadOnlySpan<T>) static method — ImmutableArray<T> in .NET 8, or your own type marked with [CollectionBuilder] — are built through that method:

csharp
[CollectionBuilder(typeof(MatrixFactory), nameof(MatrixFactory.Create))] public readonly struct Matrix : IEnumerable<int> { private readonly int[] _values; public Matrix(int[] values) => _values = values; public IEnumerator<int> GetEnumerator() => ((IEnumerable<int>)_values).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public static class MatrixFactory { public static Matrix Create(ReadOnlySpan<int> values) => new(values.ToArray()); } Matrix m = [1, 2, 3]; // routed through MatrixFactory.Create(ReadOnlySpan<int>)

Everything else uses the collection-initializer rules: the type must implement IEnumerable and offer an accessible Add that accepts one element. The interface targets IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, and IList<T> are special-cased by the compiler.

The spread element is a foreach, not a splice

csharp
int[] prefix = [1, 2]; List<int> middle = [3, 4]; int[] result = [0, .. prefix, .. middle, 5]; // 0,1,2,3,4,5

A spread source must be enumerable with foreach; it does not need to be an array or implement IEnumerable<T>, and a Span<T> qualifies. Spreading is not a pointer trick — the elements are enumerated and copied into the destination being built, which is why a spread of a lazy IEnumerable<T> executes it exactly once, at the point of construction.

Written asWhat runsAllocations
[a, b, c]three element evaluationsarray/span as per target
[.. source] where source is T[]AddRange-style copytarget storage only
[.. source] where source is IEnumerable<T>enumeration during constructiontarget storage, grown if count unknown
source.Concat(other).ToArray()iterator object, buffer, array3 or more

What the compiler actually builds

Target typeConstructionCost
T[]exact-size array, filled onceone allocation, no growth
Span<T>, ReadOnlySpan<T>inline array on the stack when the span cannot escape, otherwise an arrayzero when stack-allocated
List<T>, HashSet<T>builder using CollectionsMarshal.SetCount under .NET 8, then the collectionone collection allocation
IEnumerable<T>, IReadOnlyList<T>array plus a synthesized read-only wrappertwo allocations
ICollection<T>, IList<T>a List<T>one allocation
ImmutableArray<T>ImmutableArray.Create(ReadOnlySpan<T>)one allocation
object, var, dynamicnot convertiblecompile error
[] is not an allocation at all when the target is not modified afterwards: it becomes Array.Empty<T>(). A ReadOnlySpan<byte> built only from constants can be emitted as static data instead of being constructed per call, which is why a protocol header or a lookup table reads better as a span literal than as a static array field.

Edge cases that decide performance and correctness

1. var and object have no target, and nested literals need one

csharp
var items = [1, 2, 3]; // CS9176: no target type object boxed = [1, 2, 3]; // CS9174: cannot initialize 'object' int[][] grid = [[1, 2], [3, 4]]; // fine: element target is int[] var grid2 = [[1, 2], [3, 4]]; // CS9176 again

Each nested expression is converted against the element type of its parent, so nesting works once the outermost target is stated. A cast states it too: var items = (int[])[1, 2, 3];.

2. A spread of null fails at runtime, not at compile time

csharp
int[]? maybe = null; int[] values = [.. maybe]; // NullReferenceException during construction

The spread is a foreach, and a foreach over null throws. Read the compiler warning for a nullable spread source seriously, and give the branch a target of its own when the value is optional:

csharp
int[] values = maybe is null ? [] : [.. maybe];

3. Overload resolution changes silently when a span overload appears

csharp
void Log(int[] values) { } void Log(List<int> values) { } Log([1, 2, 3]); // CS0121: ambiguous between the two Log((int[])[1, 2, 3]); // explicit target resolves it

When the candidates are a span and a non-ref type, the span wins by rule; between an interface and a concrete type, the concrete type wins; between two element conversions, the better element conversion wins regardless of the collection type. Adding Log(Span<int>) to an existing type can therefore change which overload every untyped call site binds to, without any change at those call sites.

4. Interface targets are read-only, and a fresh instance every time

csharp
IReadOnlyList<int> a = [1, 2, 3]; IList<int> b = [1, 2, 3]; // backed by List<int>: Add works b.Add(4); var x = (IReadOnlyList<int>)[1, 2, 3]; ((IList<int>)x).Add(4); // NotSupportedException: read-only wrapper

The IReadOnly* targets produce an immutable view over a private array, so writing through a cast throws. Each evaluation also builds a new array, so two collection expressions with equal contents are different objects and never compare equal by reference — the classic failure when such a value is used as a cache key.

5. Collection expressions always materialize

csharp
IEnumerable<int> seq = [.. ReadRows()]; // ReadRows() runs now, fully buffered

Unlike a LINQ query, the expression is not deferred: every element is produced before the assignment completes, and a following Where(...) filters an in-memory sequence. That is usually what you want for a snapshot, and the wrong thing when the source is large, streamed, or infinite — [..] around an infinite generator never returns.

Common mistakes

SymptomCauseFix
CS9058 "feature 'collection expressions' is not available in C# 11.0"project targets C# 11set <LangVersion>12</LangVersion> and net8.0
CS9176 "There is no target type for the collection expression"var, or a bare literal as an argumentdeclare the type, or cast: (int[])[1, 2, 3]
CS9174 "Cannot initialize type 'object' with a collection expression"target is object or a non-constructible typeuse a concrete collection type
NullReferenceException at the spreadthe spread source was nullguard the source and supply a separate [] branch
NotSupportedException on Addtarget was IReadOnlyList<T>/IEnumerable<T>declare the mutable type you actually need
Dictionary<K,V> d = [new("a", 1)] failsAdd takes two arguments, so dictionaries are not collection-initializer compatiblekeep new Dictionary<K,V> { ["a"] = 1 }
ImmutableArray<T> conversion missingpackage older than System.Collections.Immutable 8.0upgrade the package
"a constant value is expected"collection expression used as a default parameter or a constassign inside the method body

The upgrade path that avoids surprises: put the target type on every collection expression in public signatures first, replace new[] { ... } and new List<T> { ... } mechanically, then rewrite the Concat/ToArray chains as spreads — measuring after each step, because a target change from IEnumerable<T> to T[] or Span<T> is where the allocation wins actually appear.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.