.net made easy[]

C# 15 Collection Expression Arguments: with(...) Explained

All levelsLesson 305 of 325·Production .NET·13 min read·Updated

Collection expressions made creating lists short: [1, 2, 3]. But you couldn't tell the list how big to start, or tell a set to ignore upper and lower case. C# 15's with(...) element fixes that.

In lesson 056 you met collection expressions: one short bracket syntax that builds arrays, lists, sets and spans. List<string> names = ["Ann", "Bo"]; is much nicer than the old new List<string> { "Ann", "Bo" }.

But some collections need a setting when they're created. A HashSet<string> that treats "Hello" and "HELLO" as the same word needs a comparer. A list you're about to fill with 10,000 items works faster if you give it a capacity up front. Until now, the moment you needed one of these settings, you had to abandon the short syntax and go back to new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ... }.

In this lesson, you'll learn C# 15's with(...) element, which passes arguments to the collection's constructor right inside the brackets, plus the handful of rules that decide where it works.

What Is It?

The Simple Explanation

Put with(...) as the first thing inside the square brackets, and whatever you write inside its parentheses is handed to the collection when it's created. Everything after it is the list of items, exactly as before.

HashSet<string> words = [with(StringComparer.OrdinalIgnoreCase), "Hello", "HELLO", "hello"]; Console.WriteLine(words.Count); // 1: all three spellings count as the same word

The Technical Definition

Starting in C# 15, a collection expression may begin with a with(...) element. Its arguments are passed to the target type's constructor or, for types with a [CollectionBuilder] attribute, to the create method before its ReadOnlySpan<T> parameter. Normal overload resolution picks the constructor. The arguments are evaluated once, before the elements, from left to right. with(...) isn't supported for arrays or span types, and its arguments can't be dynamic.

Before C# 15

  • new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "b" }
  • Two different syntaxes, depending on whether you need a setting
  • No way to pass a capacity with [ ... ]

With C# 15

  • [with(StringComparer.OrdinalIgnoreCase), "a", "b"]
  • One syntax for every collection you create
  • [with(capacity: 1000)] pre-sizes a list

Why Does It Exist?

The Problem — Short Syntax With a Gap

Collection expressions quickly became the normal way to create collections in modern C#. But they had no slot for constructor arguments, so code kept switching between two styles: brackets for simple cases and the old new syntax whenever a comparer or capacity was needed. Mixed styles make code harder to read, especially for beginners.

The Solution — A Reserved First Slot

C# 15 reserves the first position in the brackets for an optional with(...) element. It reads naturally, as in "a set, with this comparer, containing these items", and it means one syntax now covers every case.

Big Picture

Capacity
List<int> items = [with(capacity: 10_000)]; reserves room up front
Comparer
HashSet<string> s = [with(StringComparer.OrdinalIgnoreCase), ...];
Spread still works
[with(capacity: values.Length * 2), .. values]
Not for arrays or spans
int[] a = [with(5), 1, 2]; is a compile error

How It Works

EVALUATING [with(capacity: values.Length * 2), .. values]
1. FIND THE TARGET TYPE
  • The variable is a List<string>, so the compiler knows which type to build. The arguments inside with(...) don't change that decision.
▼
2. EVALUATE THE with(...) ARGUMENTS FIRST
  • values.Length * 2 is computed once, before any element.
▼
3. CALL THE MATCHING CONSTRUCTOR
  • Normal overload resolution finds List<string>(int capacity) and creates the list with that capacity.
▼
4. ADD THE ELEMENTS, LEFT TO RIGHT
  • Then the items, here everything spread from values, are added in order.

Simple Example

string[] values = ["one", "two", "three"]; // Pass a capacity to the List<T> constructor, then spread the values in. List<string> names = [with(capacity: values.Length * 2), .. values]; Console.WriteLine($"{names.Count} items, room for {names.Capacity}"); // 3 items, room for 6 // Pass a comparer to the HashSet<T> constructor. HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), "Hello", "HELLO", "hello"]; Console.WriteLine(set.Count); // 1

Code → Meaning → Result: The list is created with room for 6 items and then filled with the 3 values. The set is created with a case-insensitive comparer, so the three spellings of "hello" are treated as one word, and only the first one is stored.

Real-World Example

A blog lets authors tag posts. People type tags in any case ("CSharp", "csharp", "CSHARP"), and the site should store each tag once and show the tags in alphabetical order. A SortedSet<string> with a case-insensitive comparer does both jobs, and now it fits in one line:

string[] typedTags = ["dotnet", "CSharp", "csharp", "Async", "DOTNET"]; SortedSet<string> tags = [with(StringComparer.OrdinalIgnoreCase), .. typedTags]; Console.WriteLine(string.Join(", ", tags)); // Async, CSharp, dotnet

And when a report is about to load a known number of rows, a capacity avoids the list repeatedly growing and copying its internal array:

int rowCount = GetRowCount(); // say, 50,000 List<Order> orders = [with(capacity: rowCount)]; foreach (Order order in ReadOrders()) { orders.Add(order); // no resizing on the way to 50,000 }

Interfaces work too, within limits. For IList<T> and ICollection<T> the compiler builds a List<T>, so IList<int> ids = [with(capacity: 100)]; is allowed. For read-only interfaces such as IEnumerable<T> and IReadOnlyList<T>, only an empty with() is accepted.

Analogy

Ordering at a Sandwich Counter

A collection expression is like ordering a sandwich by listing the fillings: cheese, tomato, lettuce. The with(...) element is the instruction you give before the fillings: "on brown bread, toasted". It changes how the sandwich is made, not what goes in it.

And just as you tell the counter about the bread before the fillings, with(...) must come first in the brackets.

Under the Hood

Common Confusion

1. "This is the same with as in records" — no, just the same word

person with { Age = 30 } from the records lesson creates a modified copy of a record. [with(...), ...] passes constructor arguments to a collection. Same keyword, two unrelated jobs, and the brackets and parentheses tell them apart.

2. "Capacity limits how many items the list can hold" — no, it's only a head start

A List<T> with capacity 100 can still grow to a million items. Capacity is just the room reserved up front, so the list doesn't have to resize while you fill it.

3. "The comparer helps the compiler choose between overloads" — no, it doesn't

If a method has two overloads, one taking List<string> and one taking HashSet<string>, then Print([with(StringComparer.OrdinalIgnoreCase), "one", "ONE"]) is an ambiguous call (error CS0121). The compiler ignores the with(...) arguments when choosing the overload. Assign the collection to a typed variable first.

Common Mistakes

Mistake 1 — Putting with(...) anywhere but first

The mistake: Writing ["a", "b", with(capacity: 10)] and getting a compile error.

The fix: with(...) must always be the first element. The settings come before the items.

Mistake 2 — Using it with arrays or spans

The mistake: Writing int[] numbers = [with(10), 1, 2, 3]; because it works for lists.

The fix: Arrays and span types (Span<T>, ReadOnlySpan<T>) don't support with(...). Their size is simply the number of elements you list. Use a List<T> if you need a capacity.

Mistake 3 — Expecting it to infer a type

The mistake: Calling a generic method Use([with(10)]) and getting error CS0411 because the type argument can't be inferred.

The fix: The capacity says nothing about the element type, and the collection has no elements to infer it from. Write the type explicitly: Use<int>([with(10)]).

When Should I Use It?

Mental Model

[with(settings), item1, item2, .. more]: settings first, then the items.
The settings go to the collection's constructor (or its builder method).
Not for arrays or spans; not used to pick between overloads.

Remember: with(...) is the "how to build it" note at the front of your shopping list.

Key Takeaway


Check Your Understanding

Three quick questions on where with(...) goes and what it does.

1. What does HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), "Hi", "HI"]; produce?

Show answer

Correct: B

Why B is correct: The with(...) argument goes to the HashSet<string> constructor that takes a comparer. With a case-insensitive comparer, "Hi" and "HI" are the same word.

Why A is incorrect: That would be true without the comparer. The with(...) element changes how the set compares items.

Why C is incorrect: In C# 15, with(...) is also valid as the first element of a collection expression. The record with is a different feature.

Why D is incorrect: with(...) isn't an element of the collection. It supplies constructor arguments.

Reinforcement: with(...) configures the collection; the rest of the brackets fill it.

2. Which line does NOT compile in C# 15?

Show answer

Correct: C

Why C is correct: Arrays and span types don't support with(...). An array's length is simply the number of elements listed.

Why A is incorrect: List<int> has a constructor that takes a capacity, so this works.

Why B is incorrect: For IList<T> the compiler creates a List<T>, and with(capacity) is one of the supported forms.

Why D is incorrect: SortedSet<string> has a constructor that accepts an IComparer<string>, and StringComparer.Ordinal is one.

Reinforcement: Lists, sets and other collection classes: yes. Arrays and spans: no.

3. In [with(capacity: n), .. items], what happens first?

Show answer

Correct: B

Why B is correct: with(...) arguments are evaluated before the elements, left to right, and the collection is created with them before any element is added.

Why A is incorrect: The collection has to exist before items can go into it, so the constructor, with its capacity, comes first.

Why C is incorrect: The order is defined: with(...) arguments first, then elements from left to right.

Why D is incorrect: Spreads work together with with(...). The capacity still reaches the constructor.

Reinforcement: Build the collection with its settings, then fill it.

That's collection expressions finished: one syntax for every collection, with settings when you need them. The next lesson extends another recent feature, C# 14's extension blocks, so you can give square-bracket indexing to types you don't own.