🎯 Key Insights: Collection expressions bring a unified, clean syntax for creating arrays, spans, lists, and more. Say goodbye to `new int[]` and `new List<T>` boilerplate!
Writing collection initialization in C# has always been verbose. Collection expressions (C# 12+) change everything.
❌ The Old Way – Verbose and Inconsistent
// ❌ Different syntax for different types
var array = new int[] { 1, 2, 3, 4, 5 };
var list = new List<int> { 1, 2, 3, 4, 5 };
var span = new Span<int>(new int[] { 1, 2, 3, 4, 5 });
var hashSet = new HashSet<int> { 1, 2, 3, 4, 5 };
// ❌ Empty collections
var emptyArray = Array.Empty<int>();
var emptyList = new List<int>();
✅ The New Way – Unified and Clean
// ✅ Same syntax for ALL collection types!
int[] array = [1, 2, 3, 4, 5];
List<int> list = [1, 2, 3, 4, 5];
Span<int> span = [1, 2, 3, 4, 5];
HashSet<int> hashSet = [1, 2, 3, 4, 5];
IEnumerable<int> enumerable = [1, 2, 3, 4, 5];
// ✅ Empty collections
int[] emptyArray = [];
List<string> emptyList = [];
HashSet<bool> emptySet = [];
// ✅ Type inference where possible
var numbers = new int[] { 1, 2, 3 }; // Still needs 'new int[]'
int[] numbers = [1, 2, 3]; // Type explicit
🚀 The Spread Operator – Combine Collections
// ✅ Spread operator (..) - Combine effortlessly
int[] first = [1, 2, 3];
int[] second = [4, 5, 6];
int[] combined = [..first, ..second, 7, 8, 9];
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
// ✅ With strings
string[] names = ["Alice", "Bob"];
string[] moreNames = [..names, "Charlie", "David"];
// Result: ["Alice", "Bob", "Charlie", "David"]
// ✅ With complex objects
var users = new[]
{
new User("Alice", 25),
new User("Bob", 30)
};
var moreUsers = [..users, new User("Charlie", 35)];
💡 Real-World: API Response Builder
// ✅ Clean API response construction
public class ApiResponseBuilder
{
public static ApiResponse<T> Success<T>(T data, string message = "Success")
{
return new ApiResponse<T>
{
Status = "Success",
Message = message,
Data = data,
// ✅ Collection expressions
Errors = [],
Metadata = new Dictionary<string, object>
[
["Timestamp", DateTime.UtcNow],
["Version", "1.0.0"]
]
};
}
public static ApiResponse<T> Error<T>(string message, params string[] errors)
{
return new ApiResponse<T>
{
Status = "Error",
Message = message,
Data = default,
// ✅ Collection expressions with spread
Errors = [..errors],
Metadata = []
};
}
}
// ✅ Usage
var response = ApiResponseBuilder.Success(
new Product { Id = 1, Name = "Laptop" },
"Product retrieved successfully"
);
var errorResponse = ApiResponseBuilder.Error<Product>(
"Validation failed",
"Name is required",
"Price must be positive"
);
📊 Collection Expressions: Before vs After
| Operation | Before | After | Char Reduction |
|---|---|---|---|
| Array Creation | new int[] { 1, 2, 3 } | [1, 2, 3] | 60% |
| List Creation | new List<int> { 1, 2, 3 } | [1, 2, 3] | 65% |
| Empty Array | Array.Empty<int>() | [] | 80% |
| Combine Arrays | first.Concat(second).ToArray() | [..first, ..second] | 70% |
💡 Pro Tip: Collection Expressions Performance
// ✅ Compiler optimizes collection expressions // Behind the scenes: // - For arrays: uses stackalloc when possible // - For lists: uses CollectionBuilder attribute // - For spans: directly creates span // ✅ Performance benchmark int[] numbers = [1, 2, 3, 4, 5]; // Optimized Span<int> span = [1, 2, 3, 4, 5]; // Stack allocation! // ⚠️ Note: Collection expressions are compile-time features // No runtime performance penalty!
📝 Summary Checklist
✅ Use [..] for all collection types ✅ Use spread (..) for combining collections ✅ Use [] for empty collections ✅ Use in method parameters for cleaner calls ✅ Use with Dictionary initialization ❌ Don't use with dynamic types ❌ Don't use when collection type cannot be inferred

