C# 15 Adds Custom Comparer Support to Collection Expressions
C# 15 preview introduces the with(...) element, letting developers pass custom comparers and capacity arguments directly inside collection expressions for HashSet and List.
C# 12's collection expressions made creating lists and arrays clean and concise, but that elegance broke down whenever a collection like HashSet<T> needed a custom equality comparer, forcing developers back to verbose constructor-plus-initializer syntax. With the C# 15 preview, Microsoft has introduced a new with(...) element that can appear as the first item in a collection expression, allowing arguments such as StringComparer.OrdinalIgnoreCase or a List<T> capacity value to be specified alongside the collection's contents in a single, unified expression.
The change matters for readability: the comparer, which defines how equality and uniqueness work, now sits visibly at the top of the expression rather than being buried in a separate constructor call. A practical example shows a custom IEqualityComparer<User> comparing users by email address, placed directly inside a HashSet<User> collection expression via with(...). The rule that with(...) must always be the first element ensures reviewers immediately see how the collection's behavior is configured, without scanning through the entire list of values.
The feature isn't limited to HashSet<T>; it also supports passing a capacity argument to List<T> or a comparer that affects ordering in a SortedSet<T>. Notably, it can't be used with var, since the compiler needs an explicit target type to know which collection to construct — a deliberate tradeoff favoring clarity over inference magic.
Developers should note that this is currently a C# 15 preview feature, supported by preview versions of .NET 11, and requires setting LangVersion to preview in the project file before using it in real code.