Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The concise way to initialize an array of reference type object

Tags:

c#

linq

I wonder if there is better way to initialize an array of reference type object, like this.

Queue<int>[] queues = new Queue<int>[10];
for (int i = 0; i < queues.Length; i++)
    queues[i] = new Queue<int>();

I tried Enumerable.Repeat, but all elements in the array refer to same instance,

Queue<int>[] queues = Enumerable.Repeat(new Queue<int>(), 10).ToArray();

I also tried Array.ForEach, but it doesn't work without ref keyword:

Queue<int>[] queues = Array.ForEach(queues, queue => queue = new Queue<int>());

any other idea?

like image 896
lidong Avatar asked Dec 27 '22 18:12

lidong


1 Answers

You could use this:

Enumerable.Range(0,10).Select(_=>new Queue<int>()).ToArray()

But IMO your first example is perfectly fine too.

like image 124
CodesInChaos Avatar answered Dec 29 '22 11:12

CodesInChaos