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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With