Collection Expression Syntax
Initialize arrays, lists, and spans uniformly.
Collection Expressions (C# 12)
C# 12 introduces collection expressions: a single square-bracket syntax to create arrays, lists, spans, and more. Instead of new int[] { 1, 2, 3 } you simply write [1, 2, 3].
using System;
int[] numbers = [1, 2, 3, 4, 5];
Console.WriteLine(string.Join(",", numbers)); // 1,2,3,4,5One Syntax, Many Targets
The same [...] literal works whether the target is an array, a List<T>, or a Span<T>. The compiler picks the right construction.
using System;
using System.Collections.Generic;
int[] arr = [1, 2, 3];
List<int> list = [4, 5, 6];
Span<int> span = [7, 8, 9];
Console.WriteLine(arr.Length + " " + list.Count + " " + span.Length);All lessons in this course
- Collection Expression Syntax
- The Spread Element
- Target Typing Collections
- Collection Builders