c# - best way to initialize an array of reference type object

Posted by lidong on Stack Overflow See other posts from Stack Overflow or by lidong
Published on 2012-09-07T21:20:51Z Indexed on 2012/09/07 21:38 UTC
Read the original article Hit count: 133

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ