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

753 views Asked by At

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.

  • Is there an implicit 'new List' when the Range Operator is used this way?
  • I understand that the left-hand-side of the .. operator can be blank (implied zero), but I don't understand how the enumerable range can be used as the right-hand-side of the .. operator.

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.

1

There are 1 answers

0
Tim Schmelter On BEST ANSWER

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").