SharpRuneOpen playground

C# 15 collection expression arguments

Pass a comparer or capacity through with(...) without giving up bracket syntax.

  • 15 min
  • Read, predict, then run
External .NET 11 SDK / stable C# 15. This project does not run in SharpRune's .NET 9 playground.

Read or download the complete SDK project, then follow its setup on your computer. The separate C# companion practice below runs in SharpRune’s .NET 9 console environment.

At a glance

Constructor call here, with(...) in C# 15

SharpRune sample (.NET 9)
  • new HashSet<string>(StringComparer.OrdinalIgnoreCase)
  • Names added in a loop
  • new List<int>(capacity: 8) { 1, 2, 3 }
External project (C# 15)
  • [with(StringComparer.OrdinalIgnoreCase), .. incoming]
  • [with(capacity: 8), 1, 2, 3]
  • with(...) must be the first element
  • Not available for arrays or spans

Both versions pass StringComparer.OrdinalIgnoreCase and a capacity of eight, so both print names:2 and capacity:8. Only the external .NET 11 project compiles the with(...) element.

The concept and environment

C# 15 lets a collection expression begin with a with(...) element whose arguments go to the target collection's constructor or collection-builder method. That closes a gap in the C# 12 syntax: a HashSet that needed a case-insensitive comparer, or a List with a known capacity, previously had to be created with an explicit constructor call. The external .NET 11 project builds both with brackets. SharpRune's .NET 9 companion writes the older constructor form on purpose. It compares the resulting collections; it does not compile or emulate the new element.

Walk through the portable program

The portable program constructs a HashSet with StringComparer.OrdinalIgnoreCase, then adds Ada, ADA and Sam. The comparer treats the first two names as equal, so the set keeps two entries and the lookup for lowercase ada succeeds. The List is created with capacity eight and three initial elements. Output is names:2, ada:True, items:3 and capacity:8. Count and capacity are separate facts: the list holds three items while its backing array has room for eight. Predict each line from the constructor arguments before running the program.

Compile the genuine external feature

In the external project, [with(StringComparer.OrdinalIgnoreCase), .. incoming] passes the comparer to the HashSet constructor and then adds the spread elements. [with(capacity: 8), 1, 2, 3] selects the List constructor that takes a capacity. The project targets net11.0 and selects language version 15.0 without any preview switch, so a successful build exercises the stable feature. Its output matches the companion line for line. Save the supplied files in one directory and run the documented project command with a .NET 11 SDK installed. Read the comparer argument as part of the set's contract, not as a formatting detail.

Pitfalls and limits

The with(...) element must come first, and its arguments are evaluated before any element expression. It is not available for arrays or span targets, which have no constructor to receive arguments. For IList and ICollection targets only an optional capacity is accepted, and the compiler creates a List; IEnumerable and IReadOnlyList accept only an empty with(). The arguments also do not influence overload resolution: a comparer does not make the compiler prefer a HashSet overload over a List overload of the same method. Keep the target type explicit where the policy matters.

Practice one: isolate a contract

First, remove the comparer from both versions and predict three names and ada:False, because the default string comparer is ordinal and case-sensitive. Restore it and add a lowercase sam to the incoming array; the count should stay two. Hint: write the expected count from the comparer contract before running either program. Then change the capacity to two in both versions and add a fourth element. The count becomes four and the list grows by its own policy, so assert only that the capacity is at least the count.

Practice two: challenge an assumption

For another exercise, write a small class that derives from List of int and requires a name in its constructor, as the Microsoft Learn NamedValues example does. Confirm that [with("scores"), 1, 2] compiles in the external project, while a bare [1, 2] is rejected with CS9214 because the type has no parameterless constructor. Hint: that rejection is a compile-time result, so do not replace it with a runtime check. Write the companion version with an ordinary constructor call and a collection initializer.

Review the resulting contract

Review collection expression arguments as construction policy written beside the elements. The comparer decides what counts as a duplicate, and the capacity is an allocation hint that never changes the count. Neither is visible in the element list itself, so name the target type explicitly where the policy matters. The external source demonstrates the syntax; the portable source makes the resulting collections easy to inspect on the current engine. When reviewing code, check that a collection which needs a comparer actually receives one, whichever form constructs it.

External .NET 11 SDK / stable C# 15. This project does not run in SharpRune's .NET 9 playground.

C# 15 collection expression arguments lab

Set up the SDK project

  1. Save every listed file at its exact relative path in a fresh directory.
  2. Install a .NET 11 SDK supporting stable C# 15; check dotnet --version.
  3. Run dotnet run --project FeatureLab.csproj. Keep this external code separate from the .NET 9 playground.

Download complete SDK project ↗

Project files

Program.csDownload file ↗
Program.cs
string[] incoming = ["Ada", "ADA", "Sam"];
HashSet<string> names = [with(StringComparer.OrdinalIgnoreCase), .. incoming];
List<int> buffer = [with(capacity: 8), 1, 2, 3];
Console.WriteLine($"names:{names.Count}");
Console.WriteLine($"ada:{names.Contains("ada")}");
Console.WriteLine($"items:{buffer.Count}");
Console.WriteLine($"capacity:{buffer.Capacity}");
FeatureLab.csprojDownload file ↗
FeatureLab.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <LangVersion>15.0</LangVersion>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

Expected result

Expected console output, in this order: names:2 ada:True items:3 capacity:8 The portable companion compares the same small rule using older syntax; it does not compile or emulate the new feature.

Use the listed SDK and dependencies for this project. Open C# practice runs the separate portable exercise.

C# companion practice

Program.cs
using System;
using System.Collections.Generic;
string[] incoming = ["Ada", "ADA", "Sam"];
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string name in incoming) names.Add(name);
var buffer = new List<int>(capacity: 8) { 1, 2, 3 };
Console.WriteLine($"names:{names.Count}");
Console.WriteLine($"ada:{names.Contains("ada")}");
Console.WriteLine($"items:{buffer.Count}");
Console.WriteLine($"capacity:{buffer.Capacity}");
Open C# practice

C# practice output

names:2
ada:True
items:3
capacity:8
Try this
Run the constructor form here, then build the external with(...) version. The comparer decides the count; the capacity never does.

Further reading