Collection expressions

C# 12.0 .NET 8.0

Published Updated Author Jeffrey T. Fritz Reading time

Use a unified, concise syntax to initialize arrays, lists, spans, and other collections with cleaner code and optional spread operators for composition.

Collection expressions, introduced in C# 12.0 (.NET 8.0), provide a unified syntax for creating collections. Instead of new List<int> { ... } or new[] { ... }, you can use [...] directly, and the compiler infers the target collection type. The spread operator (..) allows combining collections easily. This feature makes collection initialization more readable and reduces ceremony.

Why it matters

  • Cleaner, more consistent syntax across all collection types (arrays, lists, spans, etc.).
  • The spread operator (..) enables elegant composition and flattening of collections.
  • The compiler infers collection type from context, reducing explicit type declarations.
  • Improves readability and aligns C# with syntax in modern languages like Python and JavaScript.

Cautions

  • Collection expression syntax requires type inference context; always ensure the compiler can determine the target type from assignment or parameter type.
  • The spread operator creates a copy of the collection, which has performance implications for large collections.
  • Some older custom collection types may not support collection expression syntax; verify compatibility with your collection types.
  • Empty collection expressions [] are valid but require explicit type context to avoid ambiguity.

Unified syntax for array and list creation

Collection expressions provide a consistent syntax for creating arrays, lists, and other collections, making initialization cleaner and less verbose.

Valid since C# 12.0

Without var

// Array
int[] numbers = new int[] { 1, 2, 3, 4, 5 };

// List
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

// Span
Span<int> values = new Span<int>(new int[] { 10, 20, 30 });

With var

// Array
int[] numbers = [1, 2, 3, 4, 5];

// List
List<string> names = ["Alice", "Bob", "Charlie"];

// Span
Span<int> values = [10, 20, 30];

Spread operator for combining collections

The spread operator (`..`) makes it easy to combine existing collections into a new one without explicit loops or LINQ.

Valid since C# 12.0

int[] first = [1, 2, 3];
int[] second = [4, 5];
int[] third = [6];

// Combine collections with spread operator
int[] combined = [..first, ..second, ..third];
// Result: [1, 2, 3, 4, 5, 6]

Console.WriteLine(string.Join(", ", combined));

Learn more

Collection expressions (Microsoft Learn)