-3

What is the language grammatical problem in my code? I want to declare an array of queues. Is this the right way to declare and use them?

   public static void Main(string[] args)
    {
        Queue<int>[] downBoolArray = new Queue<int>[8]();
        downBoolArray[0].Enqueue(1);
    }
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
deepsigner
  • 33
  • 1
  • 6

3 Answers3

4

Your first problem is a syntax error: new Queue<int>[8]() should be new Queue<int>[8].

Once declared with the correct syntax, when you attempt to use an element of the array (downBoolArray[0].Enqueue(1)) you will encounter a NullReferenceException because array elements initialise to their default values which in the case of a reference type is null.

You could instead initialise your array with non-null seed values using a single line of LINQ:

Queue<int>[] downBoolArray = Enumerable.Range(1,8).Select(i => new Queue<int>()).ToArray();

The arguments to Range specify that we need 8 'entries' in our sequence; the Select statement creates a new Queue<int> for each item; and the ToArray call outputs our sequence as an array.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
0

You need to initialize each element in your array

void Main()
{
    Queue<int>[] downBoolArray =new Queue<int>[10];

    for (int i = 0; i < downBoolArray.Length; i++)
        downBoolArray[i] = new Queue<int>();
    downBoolArray[0].Enqueue(1);
}
santosh singh
  • 27,666
  • 26
  • 83
  • 129
-2

You've created an array of null values.

What you want is something like this:

public static void Main(string[] args) {

    var queues = new Queue<int>[8];

    // Possibly some other stuff

    // Initialise all values
    for (var i = 0; i < queues.Length; i++) {
        // Accounting for maybe already sporadically initialising values
        queues[i] = (queues[i]) ?? new Queue<int>();

    }
    // Do whatever

}
SimonC
  • 1,547
  • 1
  • 19
  • 43