pks
pks

Reputation: 145

What is a collection expression when instantiating a List<T>

I don't understand what Intellisense is suggesting as a replacement for my existing code (pictured here) enter image description here

In case the image gets deleted later, the Intellisense suggestion that is pictured suggests replacing

List<int> x = new List<int>();
x.AddRange(Enumerable.Range(0, 300));

with

List<int> x = [.. Enumerable.Range(0, 300)];

I assume that .. is the Range Operator that was introduced in C# 8.0, but there is no documentation surrounding this suggested usage.

If someone could explain what's happening "under the hood" of this specific usage of [x..y] in regards to instantiating a new List, I'd appreciate it.

Upvotes: 6

Views: 3516

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460238

As Jeanot Zubler commented: this is the new collection expression of C# 12, which was released yesterday with .NET 8.

It allows for example this syntax:

int[] row0 = [1, 2, 3];
int[] row1 = [4, 5, 6];
int[] row2 = [7, 8, 9];
int[] single = [..row0, ..row1, ..row2];

or in your case this:

List<int> x = [.. Enumerable.Range(0, 300)];

The .. is a kind of "flatten"-operator if i understood it correctly (officially: "spread operator").

Upvotes: 7

Related Questions