DEV Community

Cover image for C# 15 Unpacked: Collection Expressions Finally Take Arguments
Giorgi Kobaidze
Giorgi Kobaidze Subscriber

Posted on

C# 15 Unpacked: Collection Expressions Finally Take Arguments

Solves constructor argument limits with new syntax

All the code in this series is available on GitHub. Clone it, run it, and try breaking it yourself.

GitHub logo georgekobaidze / dotnet11-playground

A lightweight playground repository for experimenting with and testing new features introduced in .NET 11 and C# 15.

.NET 11 & C# 15 Playground

.NET 11 & C# 15 Playground

A lightweight playground repository for experimenting with and testing new features introduced in .NET 11 and C# 15.

Use it to explore language changes, try out APIs, and validate ideas in isolation without production constraints. Each feature lives in its own small project, often with a "before" and "after" version so you can see what the new feature actually changes.

What's inside

Project Feature Description
Unions Union types Console examples: the login flow (before and after unions), plus samples for parsing input, a state machine, user commands, and combining types you don't own.
UnionsWebApi Union types A minimal API that returns a union from a service and maps each outcome to an HTTP response.
ClosedHierarchies Closed hierarchies An order status modeled as an abstract record (before) and a closed record (after), so a switch over every subtype is exhaustive without a discard arm.
…

Follow me on GitHub for more updates!


Table of Contents


Collection Expressions, a Quick Recap

C# 12 gave us collection expressions, and they quickly became one of my favorite small features. One syntax for almost every collection type:

int[] numbers = [1, 2, 3];
List<string> names = ["Jane", "John"];
HashSet<int> unique = [1, 2, 2, 3];
Span<int> span = [4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

Square brackets, a few values, done. You can even spread other collections into them with ..:

string[] moreNames = ["Charlie", "Dave"];
List<string> everyone = ["Jane", "John", .. moreNames];
Enter fullscreen mode Exit fullscreen mode

Clean, short, and consistent. Well, until it isn't.


The Catch

Collection expressions had one annoying limitation: there was no way to pass arguments to the collection's constructor.

That sounds like a small thing, until you need one. And you need one more often than you'd think:

  • A HashSet<string> that ignores case needs a comparer.
  • A List<T> you plan to keep filling benefits from an initial capacity.
  • A SortedSet<T> with a custom sort order needs a comparer too.

The moment you needed any of these, the nice syntax was gone, and you were back to the old way:

var tags = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "dotnet", "csharp" };

var names = new List<string>(capacity: 100);
names.AddRange(seed);
Enter fullscreen mode Exit fullscreen mode

It works, but it's a step backwards. Two syntaxes for the same job, and you had to switch between them depending on whether you needed a constructor argument.


But Those Times Are Over

C# 15 fixes this with a new element: with(...). You put it first in the collection expression, and its arguments go straight to the collection's constructor (or factory method):

HashSet<string> tags = [with(StringComparer.OrdinalIgnoreCase), "dotnet", "csharp"];

List<string> names = [with(capacity: 100), .. seed];
Enter fullscreen mode Exit fullscreen mode

That's the whole feature. A few rules to keep in mind:

  • with(...) must come first. It's not a regular element. It configures the collection before any elements go in.
  • It works with everything else. You can combine it with regular elements and spreads (..) in the same expression.
  • Named arguments work too. with(capacity: 100) reads much better than a bare with(100).

Real Examples

Let's look at a few practical cases.

A case-insensitive set

Tags, usernames, file extensions: anything where "DotNet" and "dotnet" should count as the same thing.

HashSet<string> tags = [with(StringComparer.OrdinalIgnoreCase), "dotnet", "DotNet", "DOTNET", "csharp"];

Console.WriteLine(tags.Count); // 2
Enter fullscreen mode Exit fullscreen mode

Four strings go in, but only two come out, because the comparer treats all three spellings of "dotnet" as equal.

Preallocating capacity

If you're building a list that will keep growing, giving it an initial capacity avoids repeated resizing as it fills up:

string[] seed = ["one", "two", "three"];

List<string> names = [with(capacity: 100), .. seed];

Console.WriteLine($"Count: {names.Count}, Capacity: {names.Capacity}"); // Count: 3, Capacity: 100
Enter fullscreen mode Exit fullscreen mode

The list starts with three items but has room for 100, so adding more later won't trigger a resize.

A custom sort order

A SortedSet<T> sorts in ascending order by default. Want the highest scores first? Pass a comparer:

SortedSet<int> scores = [with(Comparer<int>.Create((a, b) => b.CompareTo(a))), 42, 7, 99, 15];

Console.WriteLine(string.Join(", ", scores)); // 99, 42, 15, 7
Enter fullscreen mode Exit fullscreen mode

Same idea every time: configure the collection with with(...), then list the elements. One syntax, no matter what the collection needs.


A Glimpse of What's Next

This feature is small, but it's also groundwork. Microsoft has said that collection expression arguments are necessary for the upcoming dictionary expressions syntax.

That makes sense. Dictionaries are probably the collection type that needs a comparer most often (case-insensitive keys, anyone?). Once dictionaries get their own collection expression syntax, with(...) is what will let you pass that comparer in.

So when dictionary expressions arrive, remember: this is the feature that paved the way.


Wrapping Up

Collection expression arguments close one of the biggest gaps that kept pushing us back to the old collection syntax.

Quick recap:

  • Before C# 15, collection expressions couldn't pass arguments to a constructor, so comparers and capacities meant going back to the old syntax.
  • C# 15 adds with(...), which forwards arguments to the collection's constructor or factory method.
  • with(...) must be the first element, and it works alongside regular elements and spreads.
  • It lays the groundwork for dictionary expressions in a future version of C#.

All the code from this article is in my .NET 11 playground: dotnet11-playground.

What's the first collection in your codebase you'd rewrite with with(...)? Let me know in the comments. 👇


Let's stay connected!

Top comments (3)

Collapse
 
timmyzinin profile image
Tim Zinin •

Keeping the comparer inside the same brackets as the values removes the awkward switch between two styles. In your playground tests, did anything about the rule that with(...) comes first catch you by surprise?

Collapse
 
georgekobaidze profile image
Giorgi Kobaidze •

Not really. It was pretty intuitive.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.