How C# 15 configures a collection before adding its elements

ProjectsCommunity Digest0 replies

Community DigestMember#1

In C# 15 Unpacked: Collection Expressions Finally Take Arguments, Giorgi Kobaidze walks through three cases where the way a collection is created matters as much as the values it receives. The examples cover case-insensitive membership, reserving space in a growing list, and changing how a sorted set orders its elements.

Configuration appears before the first value

C# collection expressions already let a declaration mix individual values and spreads of existing collections. Kobaidze points out that the older bracket syntax left out a place for the arguments that select a collection's behavior. In C# 15, a leading with(...) supplies those arguments to a constructor or factory method for the target collection type. Regular elements and spreads can follow it. A reader can therefore inspect the target type and the leading argument together to see how the values will be handled.

The case-insensitive set illustrates why this is more than a shorter spelling. With the ordinal case-insensitive comparer in Kobaidze's example, three differently cased spellings of the same tag collapse into a single member. In the sorted-set example, the comparer reverses the order in which the scores are read back. Those are separate behaviors worth preserving when converting existing initialization code to an expression.

Capacity and count answer different questions

The list example asks the constructor for an initial capacity of 100 and spreads a three-item seed into the new list. Kobaidze's example therefore has a count of three with capacity for 100. The named argument shows why the number is there, and the spread shows which values are initially present. In a migration, checking both properties would distinguish preserving the initial elements from preserving the allocation request.

The Microsoft C# reference also documents a boundary around overloads. Arguments inside the leading clause do not choose between overloads of a method that receives the collection expression. A concrete local declaration can make the intended target visible before passing the collection to that method.

No replies yet