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.

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
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 collapseThe element type does not have to be constant; any expression works, and the result is evaluated left to right:
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:
[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
int[] prefix = [1, 2];
List<int> middle = [3, 4];
int[] result = [0, .. prefix, .. middle, 5]; // 0,1,2,3,4,5A 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 as | What runs | Allocations |
|---|---|---|
[a, b, c] | three element evaluations | array/span as per target |
[.. source] where source is T[] | AddRange-style copy | target storage only |
[.. source] where source is IEnumerable<T> | enumeration during construction | target storage, grown if count unknown |
source.Concat(other).ToArray() | iterator object, buffer, array | 3 or more |
What the compiler actually builds
| Target type | Construction | Cost |
|---|---|---|
T[] | exact-size array, filled once | one allocation, no growth |
Span<T>, ReadOnlySpan<T> | inline array on the stack when the span cannot escape, otherwise an array | zero when stack-allocated |
List<T>, HashSet<T> | builder using CollectionsMarshal.SetCount under .NET 8, then the collection | one collection allocation |
IEnumerable<T>, IReadOnlyList<T> | array plus a synthesized read-only wrapper | two allocations |
ICollection<T>, IList<T> | a List<T> | one allocation |
ImmutableArray<T> | ImmutableArray.Create(ReadOnlySpan<T>) | one allocation |
object, var, dynamic | not convertible | compile 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
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 againEach 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
int[]? maybe = null;
int[] values = [.. maybe]; // NullReferenceException during constructionThe 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:
int[] values = maybe is null ? [] : [.. maybe];3. Overload resolution changes silently when a span overload appears
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 itWhen 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
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 wrapperThe 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
IEnumerable<int> seq = [.. ReadRows()]; // ReadRows() runs now, fully bufferedUnlike 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
| Symptom | Cause | Fix |
|---|---|---|
| CS9058 "feature 'collection expressions' is not available in C# 11.0" | project targets C# 11 | set <LangVersion>12</LangVersion> and net8.0 |
| CS9176 "There is no target type for the collection expression" | var, or a bare literal as an argument | declare the type, or cast: (int[])[1, 2, 3] |
| CS9174 "Cannot initialize type 'object' with a collection expression" | target is object or a non-constructible type | use a concrete collection type |
NullReferenceException at the spread | the spread source was null | guard the source and supply a separate [] branch |
NotSupportedException on Add | target was IReadOnlyList<T>/IEnumerable<T> | declare the mutable type you actually need |
Dictionary<K,V> d = [new("a", 1)] fails | Add takes two arguments, so dictionaries are not collection-initializer compatible | keep new Dictionary<K,V> { ["a"] = 1 } |
ImmutableArray<T> conversion missing | package older than System.Collections.Immutable 8.0 | upgrade the package |
| "a constant value is expected" | collection expression used as a default parameter or a const | assign 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 toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.