Csharp Collection Expression
In this tutorial, you'll learn about C# Collection Expression. We cover key concepts, practical examples, and best practices.
You create a list with three items: new List<int> { 1, 2, 3 }. An array is new int[] { 1, 2, 3 }. Each collection type has its own creation syntax. Collection expressions (C# 12) unify them with a single [...] syntax.
Wrong
int[] array = new int[] { 1, 2, 3 };
List<int> list = new List<int> { 1, 2, 3 };
Span<int> span = new Span<int>(new int[] { 1, 2, 3 });
Output: Three different creation patterns for three similar types.
Right
int[] array = [1, 2, 3];
List<int> list = [1, 2, 3];
Span<int> span = [1, 2, 3];
ReadOnlySpan<int> ros = [1, 2, 3];
Output: Same types and values. The [...] syntax works for any collection type.
Collection expressions also support the spread operator .. to combine collections:
int[] first = [1, 2, 3];
int[] second = [4, 5, 6];
int[] combined = [..first, ..second, 7, 8]; // [1, 2, 3, 4, 5, 6, 7, 8]
Prevention
- Use
[...]as the universal collection creation syntax in new code. - Use the spread operator
..to merge collections inline. - Use collection expressions in method arguments:
ProcessItems([1, 2, 3]). - Use collection expressions in switch expressions for concise pattern results.
- Use
[]for empty collections instead ofArray.Empty<T>()ornew List<T>(). - Use collection expressions with
IEnumerable<T>parameters — the compiler selects the optimal concrete type.
Common Mistakes with collection expression
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Collection expressions are used in DodaZIP for building archive entry lists. For more C# features, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro