Collection expressions unify collection creation: the same square-bracket syntax works for arrays, List<T>, Span<T>, HashSet<T> and many other types.
Basic syntax
int[] numbers = [1, 2, 3];
List<string> names = ["Anna", "Luca"];
HashSet<char> vowels = ['a', 'e', 'i', 'o', 'u'];
ReadOnlySpan<byte> header = [0x50, 0x4B, 0x03, 0x04];
List<int> empty = [];
The compiler chooses the most efficient way to build each type: for example a span of constants can point directly at the program's data without allocating.
The spread operator
With .. you insert all the elements of another collection:
string[] basic = ["read"];
string[] admin = [.. basic, "write", "delete"];
IEnumerable<int> Even(int max) => [.. Enumerable.Range(0, max).Where(n => n % 2 == 0)];
In method signatures
Collection expressions work wherever the target type is known, including as arguments:
void Notify(IReadOnlyList<string> recipients) { /* ... */ }
Notify(["info@company.com", "support@company.com"]);
Why adopt them
- Uniform code: changing the collection type does not require rewriting the initialisation.
- Performance: the compiler optimises construction for each type.
- Readability: spread replaces many calls to
ConcatandAddRange.
Comments (0)
No comments yet.