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?
You could use this:
Enumerable.Range(0,10).Select(_=>new Queue<int>()).ToArray()
But IMO your first example is perfectly fine too.
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