Since C# 12 introduced collection expressions like [1, 2, 3], developers loved the shorter syntax—until they needed to pass a starting capacity to a List<T> or a custom comparer to a SortedSet<T>. Previously, you had to abandon bracket syntax and go back to new List<T>(capacity). In C# 15 (.NET 11), the new with(...) collection expression argument lets you pass constructor or factory parameters right inside [...].
[ with(arguments), initial items, ..spreadItems ]
Why Collection Expression Arguments Matter
- Avoid extra list reallocations: Pass
with(capacity: 100)when you already know roughly how many student records you will add. - Keep custom sorting inline: Pass a
Comparer<T>orStringComparer.OrdinalIgnoreCasedirectly inside aHashSet<T>orSortedSet<T>expression. - Consistent modern C# style: Combine
with(...)with spread elements (..existingItems) in one expression.
Try C# 15 with(...) in a Student Leaderboard Example
Create a .NET 11 console app (dotnet new console -n CollectionArgsDemo) and replace Program.cs:
// 1. Pre-size a List while adding starter student names
List<string> enrolledStudents = [with(capacity: 50), "Aarav", "Maya", "Liam"];
Console.WriteLine($"Count: {enrolledStudents.Count}, Capacity: {enrolledStudents.Capacity}");
// 2. Build a case-insensitive HashSet without calling new HashSet<string>(...)
HashSet<string> courseCodes = [with(StringComparer.OrdinalIgnoreCase), "CS101", "cs101", "SQL202"];
Console.WriteLine($"Unique courses: {courseCodes.Count}"); // Output: 2
// 3. Pass a descending comparer to SortedSet using spread syntax
int[] incomingScores = [78, 95, 88, 91];
var highestFirst = Comparer<int>.Create((left, right) => right.CompareTo(left));
SortedSet<int> leaderboard = [with(highestFirst), .. incomingScores, 99];
Console.WriteLine("Leaderboard: " + string.Join(", ", leaderboard));
// Output: 99, 95, 91, 88, 78
Three Rules to Remember
- Always place
with(...)first: Thewith(...)element must be the very first entry inside[...]. - Named or positional arguments work: Just like a normal method or constructor call, you can write
with(capacity: 50)orwith(50). - Matches target collection constructors: The arguments inside
with(...)must match a constructor on the target type (such asList<T>(int capacity)orHashSet<T>(IEqualityComparer<T>)).
Practice
- Create a
HashSet<string>usingwith(StringComparer.OrdinalIgnoreCase)and test adding"React"and"react". - Create a
List<int>withwith(capacity: 20)and combine two arrays using..firstBatchand..secondBatch. - Try moving
with(...)to the end of the bracket list to observe the compiler error rule firsthand.
Continue learning: C# Tutorials and Examples.
References: C# Documentation (Microsoft Learn).
No comments:
Post a Comment
Please do not enter any spam link in the comment box.