Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 182 ยท Collections

Collection Expressions and Spread

Learn C# 12 collection expressions - the [1, 2, ..other] syntax, target types, the spread element, empty [], custom collection builders and the performance behind them.

Before C# 12, creating a collection meant choosing a different syntax for each type: new int[] { 1, 2, 3 } for an array, new List<int> { 1, 2, 3 } for a list, ImmutableArray.Create(1, 2, 3) for an immutable array, and stackalloc or new[] for spans. Joining two collections meant calling Concat, AddRange or writing a loop. Collection expressions replace all of that with one uniform syntax: square brackets around the items.

C#
int[] numbers = [1, 2, 3];
List<string> names = ["Ann", "Bo"];

This lesson explains how the compiler decides which collection type to build (the "target type"), how the spread element .. splices other collections in, how to write an empty collection, how to make your own types work with the syntax, and what the compiler generates so you know when it is as fast as hand-written code. Collection expressions arrived in C# 12 / .NET 8 and work in every project that targets a modern language version. For the collection types themselves, see Arrays, List of T and HashSet and SortedSet.

The basic syntax

A collection expression is a comma-separated list of elements inside [ and ]. What you get depends entirely on the type it is assigned to.

C# One syntax, many collection types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same three items produced six different kinds of collection. The expression itself has no type; the compiler looks at where it is going (the target type) and builds the right thing. That is why the syntax is described as "target-typed".

Target types: what can be built

A collection expression can be converted to:

  • arrays and Span<T> / ReadOnlySpan<T>;
  • any type with a collection initializer pattern: it implements IEnumerable and has an Add method, such as List<T>, HashSet<T>, Queue<T>, Stack<T> and SortedSet<T>;
  • the interfaces IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T> and IList<T>;
  • types that declare a collection builder (explained below), such as ImmutableArray<T>.

It cannot become a Dictionary<TKey, TValue>; as of C# 14 there is no dictionary expression, and you keep using the { [key] = value } initializer for dictionaries.

Where the target type comes from

Anything that tells the compiler a type works: a variable declaration, a method parameter, a return type, a property, a ternary branch with a typed other side, or a cast.

C# Collection expressions as arguments and return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Total([10, 20, 30]) passes a collection expression straight into a parameter; no new is needed. The last method uses params IEnumerable<string>, a params collection, available since C# 13, so a caller can also write PrintAll("alpha", "beta") without brackets.

var has no natural type

Because the expression has no type of its own, you cannot write var x = [1, 2, 3];. The compiler has nothing to infer from. Name the type, or use a typed helper:

C# var cannot infer a collection expression (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS9176: There is no target type for the collection expression. Replace var with int[], List<int> or whatever you want. (An array initializer with new[] { 1, 2, 3 } still works with var.)

The spread element

Inside a collection expression, ..expression inserts every item of another collection at that point. That is the spread element. The spread source can be any IEnumerable<T> (or span), and you can mix spreads and single items freely.

C# Spread: combine and extend collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The spread is evaluated once, in order, when the expression runs. The result is a new collection: changing copy does not affect first. That makes [..source] a neat way to take a snapshot of a list or to convert one collection type into another (HashSet<int> set = [..list];).

Spread is also the neatest way to conditionally include items:

C# Optional items with spread and the ternary operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A branch of ?: that is a collection expression needs a target type, which the cast or the other branch supplies. If both branches are bare [...] the compiler cannot decide, which is why the first one has a cast and the second uses Array.Empty<string>() as its typed partner.

The empty collection

[] is an empty collection of whatever type is expected. It is better than new List<int>() for brevity, and for arrays and read-only interfaces it is better for performance too: the compiler uses a shared cached empty array rather than allocating a new one.

C# Empty collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

All empty arrays can share one instance because an empty array has nothing to modify. A mutable List<string> names = [] must of course allocate a fresh list each time, since you are going to change it.

What the compiler generates

You do not pay for the nicer syntax. The compiler picks an efficient strategy for each target:

  • Arrays: allocates the array at its final size and fills it in place. If everything is spread from collections with a known length, it adds the lengths up first, so there are no intermediate copies.
  • List<T>: creates a list with the right capacity, then fills it, avoiding repeated growth.
  • Span<T> and ReadOnlySpan<T>: for constant elements it can point straight into the program's read-only data, with no allocation at all. A ReadOnlySpan<int> primes = [2, 3, 5, 7]; costs nothing at run time. A non-constant Span<T> of modest size may live on the stack through an "inline array".
  • Interfaces such as IEnumerable<T>, IReadOnlyList<T>: the compiler is free to choose the concrete type. It builds a lightweight read-only wrapper, so you must not cast the result back to List<T> and mutate it. For ICollection<T> and IList<T> it creates a List<T>.

If a method only reads its input, accept ReadOnlySpan<T>, IEnumerable<T> or IReadOnlyList<T> and let callers pass [1, 2, 3]. The caller's literal costs almost nothing, and your method works with arrays, lists and literals alike.

Spread has one performance subtlety. When the source is a plain IEnumerable<T> with unknown length, the compiler cannot size the result up front, so it falls back to collecting items first. If you spread a List<T>, array or span, it knows the count and copies in bulk, often with a single CopyTo.

Making your own type work: CollectionBuilder

Types such as List<T> work because they have an Add method. Immutable and read-only types have no Add, so they cannot use that route. .NET 8 added the [CollectionBuilder] attribute: you point it at a static factory method that receives a ReadOnlySpan<T> with all the elements. ImmutableArray<T>, ImmutableList<T> and others are marked this way.

Here is a small custom collection that opts in:

C# A custom type with CollectionBuilder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Rules for the builder method: it must be static, take a single ReadOnlySpan<T> parameter, and return the collection type. The type must implement IEnumerable<T> (or IEnumerable) so the compiler can find the element type. (We call ((IEnumerable<string>)_songs) to get an enumerator over the array; an array already implements IEnumerable<string>.)

Alternatively, a custom collection with a public parameterless constructor and an Add method works with no attribute at all, like List<T> does.

Mistakes and limits

C# Elements must convert to the element type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each element must be implicitly convertible to the element type. The compiler reports error CS0029: Cannot implicitly convert type 'string' to 'int' for "three".

A few more points to remember:

  • A collection expression creates a new collection each time it runs. In a loop, [] or [1, 2, 3] allocates (or reuses a shared empty array) every iteration. Hoist constants out of loops, or use a static readonly field.
  • Mutating through an interface target is not guaranteed to work: IEnumerable<int> items = [1, 2, 3]; may be backed by something read-only.
  • Spread elements and single items cannot be mixed up: [..5] is an error because 5 is not a collection, while [5] is a one-item collection.
  • There is no dictionary expression (yet), no with clause for passing a capacity or comparer, and you cannot spread a dictionary into a dictionary. Use new Dictionary<string, int> { ["a"] = 1 }.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What decides which kind of collection the expression [1, 2, 3] creates?

    A collection expression has no type of its own. The compiler builds an array, list, span, set or other type depending on the expected type.
  2. 2. Why does var numbers = [1, 2, 3]; not compile?

    The compiler reports CS9176: There is no target type for the collection expression. Write the type explicitly.
  3. 3. What does int[] c = [..a, 0, ..b]; do when a and b are int arrays?

    The spread element inserts each item of its source in order. The result is a new array; a and b are unchanged.
  4. 4. Which attribute lets an immutable custom type be created with a collection expression?

    CollectionBuilder names a static factory method that receives a ReadOnlySpan<T> of the elements.
  5. 5. Which target type can a collection expression NOT be converted to in C# 14?

    Dictionaries have key-value pairs and C# 14 has no dictionary expression. Use a dictionary initializer instead.

Summary

  • A collection expression [a, b, c] builds an array, list, set, span, interface or builder-based type chosen by its target type (C# 12).
  • var cannot be used, because there is no natural type (error CS9176).
  • ..source spreads the items of any collection into the new one; the result is a fresh collection.
  • [] is the empty collection of the target type; empty arrays share one cached instance.
  • The compiler sizes arrays and lists exactly and can avoid allocation entirely for constant ReadOnlySpan<T>.
  • Add [CollectionBuilder] to your own type to make it a valid target; types with Add already work.
  • Dictionaries are not supported yet; interfaces give no promise about the concrete type.

Next: Immutable, Frozen and Read-only Collections