question about the initialization of an array of generic queue

  • Thread starter Thread starter chrisben
  • Start date Start date
C

chrisben

Here are the codes

Queue<string>[] q = new Queue<string>[2];

Console.WriteLine(q[0].Count + "");

The program will crash since q[0] is null.

So my question is that what is the best way for new to initialize the array
with generic queue as the value?

I can do for statement and then do q = new Queue<string>();

But,is there a better way to do it?

Thanks

Chris
 
But,is there a better way to do it?

No, not really. Array values initialize to their default values: 0 /
false / null / etc. Assuming you want each item in the array to be a
different queue, you will need to loop and create (new) a different
object for each.

Marc
 
chrisben said:
Here are the codes

Queue<string>[] q = new Queue<string>[2];

Console.WriteLine(q[0].Count + "");

The program will crash since q[0] is null.

So my question is that what is the best way for new to initialize the
array with generic queue as the value?

I can do for statement and then do q = new Queue<string>();

But,is there a better way to do it?


Well, you can always write a reusable function for that:

static class ArrayHelper
{
static void FillUsingDefaultConstructor<T> (this T[] array) where T :
new
{
for( int i = 0; i < array.Length; i++ )
array = new T();
}
}
 
Why not use List<Queue<string>> ?

Here are the codes

Queue<string>[] q = new Queue<string>[2];

Console.WriteLine(q[0].Count + "");

The program will crash since q[0] is null.

So my question is that what is the best way for new to initialize the array
with generic queue as the value?

I can do for statement and then do q = new Queue<string>();

But,is there a better way to do it?

Thanks

Chris
 
Back
Top