Advertisement
Advanced C#, Modern C# Features (Global Usings, File-Scoped Namespaces, Top-Level Statements)

How do C# 12's collection expressions (`[1, 2, 3]`) provide a unified, type-agnostic syntax for initializing arrays, lists, and spans?

Short answer

Collection expressions use a single, consistent `[...]` syntax that the compiler adapts to whatever the TARGET TYPE actually is — an array, a List , a Span , or any type implementing the right collection-building pattern — replacing the previously inconsistent mix of 'new[]…

Save C# mock interview
Advertisement
AModel answer
Collection expressions use a single, consistent `[...]` syntax that the compiler adapts to whatever the TARGET TYPE actually is — an array, a List<T>, a Span<T>, or any type implementing the right collection-building pattern — replacing the previously inconsistent mix of 'new[] {...}', 'new List<T> {...}', and other type-specific initialization syntaxes.
int[] array = [1, 2, 3];
List<int> list = [1, 2, 3];
Span<int> span = [1, 2, 3];

int[] combined = [..array, 4, 5, ..list]; // spread operator ('..') combines collections too
Real-world example
Simplifying and unifying collection initialization syntax across arrays, lists, and spans throughout a modern C# codebase.
Likely follow-ups
  • How does the spread operator ('..') inside a collection expression work to combine multiple existing collections?
Related topics