Collection Expressions & Spread Operator (..)
1Concept
Introduced in C# 12 and enhanced in C# 13, Collection Expressions `[a, b, ..c]` provide a unified syntax for initializing arrays, `Span<T>`, `ReadOnlySpan<T>`, `List<T>`, and immutable sets with compiler-optimized memory pre-sizing.
2Architecture Diagram
[ item1, item2, ..existingList, item3 ]
│
▼
[ Compiler Pre-calculates exact capacity: 2 + existingList.Count + 1 ]
│
▼
[ Single Heap/Stack Allocation with Span Copy (Zero Resizing Overhead) ]3Code Example
C# 13 & .NET 9
using System;
using System.Collections.Generic;
public class CollectionExpressionDemo
{
public static void Main()
{
int[] baseline = [10, 20, 30];
int[] extended = [0, ..baseline, 40, 50];
Console.WriteLine($"Extended Array: [{string.Join(", ", extended)}]");
Console.WriteLine($"Length: {extended.Length}");
// Span creation with zero heap allocation!
ReadOnlySpan<char> vowels = ['a', 'e', 'i', 'o', 'u'];
Console.WriteLine($"Stack Span Vowels Length: {vowels.Length}");
}
}4Expected Output
Extended Array: [0, 10, 20, 30, 40, 50] Length: 6 Stack Span Vowels Length: 5
5Key Takeaways
- ✓Collection expressions eliminate verbose `new int[] { }` or `new List<int>()` syntax.
- ✓The spread operator (`..`) enables zero-allocation span concatenation.
- ✓The compiler automatically selects the most efficient backend data structure.