Collection expressions C# 12.0 gave us a concise [...] syntax for creating collections, but it had no way to choose how the underlying collection was constructed. If you needed a capacity or a custom comparer you had to fall back to a constructor call.
C# 15 lets you place a with(...) element first in a collection expression to pass arguments to the collection's constructor or factory method.
Code
csharp
string[] values = ["one", "two", "three"];
// Capacity passed to the List<T> constructor
List<string> names = [with(capacity: values.Length * 2), .. values];
// Comparer passed to the HashSet<T> constructor
HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), "Hello", "HELLO", "hello"];
// set contains one element as all three are equal under OrdinalIgnoreCasecsharp
string[] values = ["one", "two", "three"];
List<string> names = new(values.Length * 2);
names.AddRange(values);
HashSet<string> set = new(StringComparer.OrdinalIgnoreCase) { "Hello", "HELLO", "hello" };Notes
- The
with(...)element must be the first element in the collection expression - Arguments can be positional or named, such as
with(capacity: 100) - Arrays and spans do not accept
with(...), not even an emptywith() - Collection types with no parameterless constructor can now be targeted, as long as the expression includes
with(...) - If you have a method called
with, call it as@with(...)inside a collection expression