question about the initialization of an array of generic queue

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
 
M

Marc Gravell

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
 
B

Ben Voigt [C++ MVP]

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();
}
}
 
M

Michael J. Ryan

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top