Collection expressions

suggest change

C# 12 added collection expressions: a single syntax, [a, b, c], that creates arrays, lists, spans, sets, immutable collections and your own collection types. It replaces new[] { ... }, new List<T> { ... }, stackalloc, Array.Empty<T>() and ImmutableArray.Create(...):

// before C# 12
int[] a = new int[] { 1, 2, 3 };
List<string> b = new List<string> { "x", "y" };
IEnumerable<int> c = Array.Empty<int>();

// C# 12 and later
int[] a2 = [1, 2, 3];
List<string> b2 = ["x", "y"];
IEnumerable<int> c2 = [];

The other parts of the feature:

The older { ... } syntax is covered in Collection initializers. It still works and is still needed for dictionaries (see below).

The examples are C# 14 / .NET 10 file-based programs: save the code as app.cs and run dotnet run app.cs.

One syntax for many collection types

using System.Collections.Immutable;

int[] array = [1, 2, 3];
List<string> names = ["Ann", "Bob"];
Span<char> letters = ['a', 'b', 'c'];
ReadOnlySpan<double> weights = [0.5, 0.25, 0.25];
HashSet<int> unique = [3, 1, 3, 2];
ImmutableArray<int> frozen = [10, 20];
IEnumerable<int> seq = [1, 2];
IReadOnlyList<int> roList = [1, 2];
IList<int> list = [1, 2];

Console.WriteLine(string.Join(", ", array));
Console.WriteLine(string.Join(", ", names));
Console.WriteLine(letters.ToString());
Console.WriteLine(weights.Length);
Console.WriteLine(string.Join(", ", unique));
Console.WriteLine(string.Join(", ", frozen));
Console.WriteLine(seq.GetType().Name);
Console.WriteLine(roList.GetType().Name);
Console.WriteLine(list.GetType().Name);
1, 2, 3
Ann, Bob
abc
3
3, 1, 2
10, 20
<>z__ReadOnlyArray`1
<>z__ReadOnlyArray`1
List`1

What the compiler builds depends on the target type:

Target type What gets created
T[] an array of the exact length
Span<T> a buffer on the stack (an inline array), no heap allocation
ReadOnlySpan<T> data stored in the assembly if all items are constants, otherwise a stack buffer
List<T>, HashSet<T>, other types with Add new T() followed by Add calls (List<T> is presized)
ImmutableArray<T>, ImmutableList<T>, FrozenSet<T>, ... the type's builder method, found through [CollectionBuilder]
IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T> a compiler-generated read-only wrapper around an array
ICollection<T>, IList<T> a List<T>

The read-only interfaces get a type you can't change even by casting. A plain array assigned to IReadOnlyList<T> can be cast back to IList<T> and modified, but the compiler-generated type throws:

IReadOnlyList<int> ro = [1, 2, 3];
try { ((IList<int>)ro).Add(4); }
catch (NotSupportedException e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); }

IReadOnlyList<int> fromArr = new[] { 1, 2 };
((IList<int>)fromArr)[0] = 42;
Console.WriteLine(fromArr[0]);

try { ((IList<int>)ro)[0] = 42; }
catch (NotSupportedException e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); }
NotSupportedException: Specified method is not supported.
42
NotSupportedException: Specified method is not supported.

The empty collection []

[] is the shortest way to write an empty collection of any type. For arrays and the read-only interfaces the compiler doesn't allocate anything: it uses the shared Array.Empty<T>() instance.

int[] empty1 = [];
int[] empty2 = [];
IEnumerable<int> empty3 = [];
IReadOnlyList<int> empty4 = [];
List<int> empty5 = [];
Console.WriteLine(ReferenceEquals(empty1, empty2));
Console.WriteLine(ReferenceEquals(empty1, Array.Empty<int>()));
Console.WriteLine(ReferenceEquals(empty3, Array.Empty<int>()));
Console.WriteLine(empty4.GetType().Name);
Console.WriteLine(empty5.Capacity);
True
True
True
Int32[]
0

A mutable type such as List<T> gets a new instance every time, because callers may add to it.

[] is also handy for ImmutableArray<T>, where default and empty are different things. A default ImmutableArray<T> wraps a null array and throws on most operations. [] gives you a real empty array:

using System.Collections.Immutable;

ImmutableArray<int> empty = [];
ImmutableArray<int> dflt = default;
Console.WriteLine($"[]: IsDefault={empty.IsDefault} IsEmpty={empty.IsEmpty}");
Console.WriteLine($"default: IsDefault={dflt.IsDefault}");
[]: IsDefault=False IsEmpty=True
default: IsDefault=True

The spread element ..

..expr inserts all items of expr. You can mix spreads and single items in any order, and the spread works on anything you can foreach over: arrays, lists, spans, LINQ queries and strings.

int[] a = [1, 2];
List<int> b = [3, 4];
IEnumerable<int> evens = Enumerable.Range(1, 10).Where(x => x % 2 == 0);
int[] all = [0, ..a, ..b, ..evens, 99];
Console.WriteLine(string.Join(" ", all));

char[] chars = [.."hi", '!'];
Console.WriteLine(new string(chars));

string s = "x";
List<string> maybe = ["a", ..(s.Length > 0 ? new[] { s } : []), "z"];
Console.WriteLine(string.Join(",", maybe));
0 1 2 3 4 2 4 6 8 10 99
hi!
a,x,z

Some common uses:

The .. in a collection expression is not the range operator from Ranges. [..a] copies a, while a[..] slices it. The same .. also appears in list patterns such as [var first, ..], which match collections instead of building them. See Destructuring.

In the conditional item above, new[] { s } is needed. A spread doesn't give the ?: a target type, so at least one branch must have a type of its own. With two collection expressions it doesn't compile:

List<string> maybe = ["a", ..(s.Length > 0 ? [s] : []), "z"];
error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'collection expression' and 'collection expression'

The target type decides

A collection expression has no "natural type", so it needs a target. var doesn't work, and neither does object:

var x = [1, 2, 3];
object o = [1];
error CS9176: There is no target type for the collection expression.
error CS9174: Cannot initialize type 'object' with a collection expression because the type is not constructible.

Anywhere the type is known, you can use one: method arguments, return statements, expression-bodied members, nested collections and the branches of ?: when the result is assigned to a typed target.

Print([1, 2, 3]);
Print([]);
Console.WriteLine(Sum([1, 2, 3, 4]));

int[] Digits(bool odd) => odd ? [1, 3, 5] : [0, 2, 4];
Console.WriteLine(string.Join(",", Digits(true)));

int[][] grid = [[1, 2], [3, 4, 5], []];
foreach (var row in grid) Console.WriteLine($"[{string.Join(",", row)}]");

List<int> Evens(int n)
{
    if (n <= 0) return [];
    return [.. Enumerable.Range(0, n).Select(i => i * 2)];
}
Console.WriteLine(string.Join(",", Evens(4)));

O.Over([1, 2]);
O.Over(new[] { 1, 2 });
O.Over(new List<int> { 1, 2 });

static void Print(IEnumerable<int> xs) => Console.WriteLine($"{xs.Count()} items");
static int Sum(ReadOnlySpan<int> xs) { int s = 0; foreach (var v in xs) s += v; return s; }

static class O
{
    public static void Over(IEnumerable<int> xs) => Console.WriteLine("IEnumerable");
    public static void Over(ReadOnlySpan<int> xs) => Console.WriteLine("ReadOnlySpan");
    public static void Over(int[] xs) => Console.WriteLine("array");
}
3 items
0 items
10
1,3,5
[1,2]
[3,4,5]
[]
0,2,4,6
ReadOnlySpan
array
IEnumerable

The last three lines show overload resolution. When several overloads could take a collection expression, the compiler prefers ReadOnlySpan<T> and Span<T> over arrays and interfaces, because a span doesn't need a heap allocation. Arguments with their own type (new[] { ... }, a List<int>) pick the overload that matches that type, as before.

Dictionaries are not supported (yet)

A collection expression needs an Add method that takes a single item. Dictionary<TKey, TValue>.Add takes a key and a value, so this doesn't compile:

Dictionary<string, int> d = [new("a", 1)];
error CS9215: Collection expression type 'Dictionary<string, int>' must have an instance or extension method 'Add' that can be called with a single argument.

Use an index initializer for dictionaries: new Dictionary<string, int> { ["a"] = 1 } (see C# 6 Index Initializers). Dictionary expressions (["a": 1]) are a proposal for a future C# version.

Spans, params collections and C# 14 span conversions

A collection expression assigned to a Span<T> or ReadOnlySpan<T> doesn't touch the heap, which makes spans a good parameter type for methods that take "a few values". If all items are constants, a ReadOnlySpan<T> points straight at data in the assembly, so you can even return it from a method:

Console.WriteLine(Primes().Length);
Console.WriteLine(Join("a", "b", "c"));
Console.WriteLine(Join());
string[] more = ["x", "y"];
Console.WriteLine(Join([.. more, "z"]));
Console.WriteLine(Total(1, 2, 3));

static ReadOnlySpan<int> Primes() => [2, 3, 5, 7, 11];
static string Join(params ReadOnlySpan<string> parts) => string.Join("+", parts);
static int Total(params List<int> xs) => xs.Sum();
5
a+b+c

x+y+z
6

Since C# 13, params works with any type a collection expression can create, not only arrays. Join("a", "b", "c") is built exactly like Join(["a", "b", "c"]), so params ReadOnlySpan<T> avoids the hidden array that params T[] allocates on every call. The details are in params arrays.

A Span<T> built from non-constant values lives on the stack, so it can't leave the method:

static Span<int> Bad(int x) { Span<int> s = [x, x]; return s; }
error CS8352: Cannot use variable 's' in this context because it may expose referenced variables outside of their declaration scope

C# 14 makes span parameters easier to use with existing data. Arrays and strings always converted to spans through user-defined conversion operators, but these conversions were ignored when looking up extension methods and inferring generic type arguments. C# 14 makes them built-in language conversions, so this code compiles:

int[] scores = [7, 3, 7, 9];
Console.WriteLine(scores.CountOf(7));
Console.WriteLine(First(scores));
Console.WriteLine("hello".AsSpan().CountOf('l'));
Console.WriteLine("hello".CountOf('l'));
foreach (var s in scores.Reverse()) Console.Write($"{s} ");
Console.WriteLine();

static T First<T>(ReadOnlySpan<T> items) => items[0];

static class SpanExtensions
{
    public static int CountOf<T>(this ReadOnlySpan<T> items, T value) where T : IEquatable<T>
    {
        int n = 0;
        foreach (var item in items)
            if (item.Equals(value)) n++;
        return n;
    }
}
2
7
2
2
9 7 3 7 

With #:property LangVersion=13 the same file fails to compile:

error CS1929: 'int[]' does not contain a definition for 'CountOf' and the best extension method overload 'SpanExtensions.CountOf<int>(ReadOnlySpan<int>, int)' requires a receiver of type 'System.ReadOnlySpan<int>'
error CS0411: The type arguments for method 'First<T>(ReadOnlySpan<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
error CS1929: 'string' does not contain a definition for 'CountOf' and the best extension method overload 'SpanExtensions.CountOf<char>(ReadOnlySpan<char>, char)' requires a receiver of type 'System.ReadOnlySpan<char>'

Because span extension methods now apply to arrays, a call such as array.Reverse() could bind to MemoryExtensions.Reverse(Span<T>) (which reverses in place and returns void) instead of LINQ's Enumerable.Reverse. .NET 10 adds an Enumerable.Reverse(T[]) overload so this still returns a reversed sequence, as the output shows. If you target an older framework with C# 14, check calls like this one after upgrading.

Making your own types work

Types with an Add method

Any type that implements IEnumerable and has an accessible Add method that takes one item works with collection expressions, just as it works with collection initializers (see Collection initializers in custom classes). The compiler calls the parameterless constructor and then Add for each item.

Immutable types with [CollectionBuilder]

An immutable type has no Add method. Put [CollectionBuilder] on it and point the attribute at a static method that takes a ReadOnlySpan<T> and returns the collection. The compiler collects the items into a span (on the stack when it can) and calls that method once:

using System.Collections;
using System.Runtime.CompilerServices;

Bag<string> bag = ["x", "y"];
Console.WriteLine(bag);

SortedVec<int> v = [5, 1, 4, ..new[] { 3, 2 }];
Console.WriteLine(v);
SortedVec<int> none = [];
Console.WriteLine($"{none} count={none.Count}");

// Classic: IEnumerable + Add works with collection expressions too
class Bag<T> : IEnumerable<T>
{
    private readonly List<T> items = new();
    public void Add(T item) { Console.WriteLine($"Add({item})"); items.Add(item); }
    public IEnumerator<T> GetEnumerator() => items.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    public override string ToString() => $"Bag[{string.Join(", ", items)}]";
}

// Immutable type with no Add: tell the compiler how to build it
[CollectionBuilder(typeof(SortedVec), nameof(SortedVec.Create))]
sealed class SortedVec<T> : IEnumerable<T> where T : IComparable<T>
{
    private readonly T[] items;
    internal SortedVec(T[] items) => this.items = items;
    public int Count => items.Length;
    public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)items).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    public override string ToString() => $"SortedVec[{string.Join(", ", items)}]";
}

static class SortedVec
{
    public static SortedVec<T> Create<T>(ReadOnlySpan<T> values) where T : IComparable<T>
    {
        Console.WriteLine($"Create called with {values.Length} values");
        T[] copy = values.ToArray();
        Array.Sort(copy);
        return new SortedVec<T>(copy);
    }
}
Add(x)
Add(y)
Bag[x, y]
Create called with 5 values
SortedVec[1, 2, 3, 4, 5]
Create called with 0 values
SortedVec[] count=0

The rules for the builder:

This is how ImmutableArray<T>, ImmutableList<T>, ImmutableHashSet<T> and the frozen collections support collection expressions. For other ways to create immutable collections, see Immutable collections.

Performance compared with initializers

A collection expression is never slower than the code you would write by hand, and is often faster, because the compiler knows the final size and the target type:

var init = new List<int> { 1, 2, 3, 4, 5 };
List<int> expr = [1, 2, 3, 4, 5];
Console.WriteLine($"initializer: Count={init.Count} Capacity={init.Capacity}");
Console.WriteLine($"expression:  Count={expr.Count} Capacity={expr.Capacity}");

List<int> source = [.. Enumerable.Range(0, 100)];
List<int> copy = [.. source, 100];
Console.WriteLine($"copy:        Count={copy.Count} Capacity={copy.Capacity}");
initializer: Count=5 Capacity=8
expression:  Count=5 Capacity=5
copy:        Count=101 Capacity=101

This program measures how many bytes each form allocates (run it with dotnet run -c Release app.cs; Debug builds disable some of the optimizations):

const int N = 100_000;
Measure("new List<int> { ... }", () => { long t = 0; for (int i = 0; i < N; i++) { var l = new List<int> { i, 2, 3, 4, 5 }; t += l.Count; } return t; });
Measure("List<int> = [...]", () => { long t = 0; for (int i = 0; i < N; i++) { List<int> l = [i, 2, 3, 4, 5]; t += l.Count; } return t; });
Measure("int[] = [...]", () => { long t = 0; for (int i = 0; i < N; i++) { int[] a = [i, 2, 3, 4, 5]; t += a.Length; } return t; });
Measure("IEnumerable<int> = [...]", () => { long t = 0; for (int i = 0; i < N; i++) { IEnumerable<int> e = [i, 2, 3, 4, 5]; t += e.Count(); } return t; });
Measure("ReadOnlySpan<int> = [...]", () => { long t = 0; for (int i = 0; i < N; i++) { ReadOnlySpan<int> s = [1, 2, 3, 4, 5]; t += s.Length; } return t; });
Measure("Span<int> = [...]", () => { long t = 0; for (int i = 0; i < N; i++) { Span<int> s = [i, 2, 3, 4, 5]; t += s[0]; } return t; });

static void Measure(string label, Func<long> f)
{
    f();
    long before = GC.GetAllocatedBytesForCurrentThread();
    f();
    long bytes = GC.GetAllocatedBytesForCurrentThread() - before;
    Console.WriteLine($"{label,-28} {bytes / N,4} bytes per collection");
}
new List<int> { ... }         128 bytes per collection
List<int> = [...]              80 bytes per collection
int[] = [...]                  48 bytes per collection
IEnumerable<int> = [...]       72 bytes per collection
ReadOnlySpan<int> = [...]       0 bytes per collection
Span<int> = [...]               0 bytes per collection

The initializer allocates the List<int> object plus two internal arrays (capacity 4, then 8). The collection expression allocates the list and one array of exactly 5. IEnumerable<int> costs an array plus the small read-only wrapper. The spans allocate nothing.

For more on spans and avoiding allocations, see Performance.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents