Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing ToArray with square brackets containing two dots

Tags:

c#

I had code like this:

Queue<Foos> queue;

// ...

Foo[] foos = queue.ToArray();

However, Visual Studio gives a suggestion IDE0305 Collection initialization can be simplified , suggesting instead:

Foo[] foos = [.. queue];

The code seems to build and run correctly. What does this syntax of dots and brackets mean?

like image 340
M.M Avatar asked Sep 02 '25 14:09

M.M


1 Answers

Both [] and .. operators are supported from C# 12.

[] is the collection expression that allows the creation for the array/collection instead of the traditional way as:

// Traditional way
int[] intArray = new int[] { 1, 2, 3 };

// C# 12 Collection expression
int[] intArray = [1, 2, 3];

Meanwhile, .. is the spread operator that allows adding all the elements in the expression.

In summary, based on your existing code, it will create a new Foo array by adding all the elements from the queue.

Included the article on C# 12: Collection Expressions written by Thomas Claudius.

like image 72
Yong Shun Avatar answered Sep 05 '25 13:09

Yong Shun