0

I'm struggling to understand why accessing an object in this array throws a NullReferenceException. I initialized the array right beforehand, so what's trying to be referenced should exist. parent.rowlength and parent.collength are the size of an array initialized earlier in code, and i know they return the right values. I'm pretty much out of ideas here. Edit: I should clarify, this happens on the first iteration of the for loops. System.NullReferenceException: 'Object reference not set to an instance of an object.'

Here's the code in the picture, let me know if you need to see more.

        RectangleShape[,] cells = new RectangleShape[parent.rowLength, parent.colLength];
        for (int i = 0; i < parent.rowLength; i++)
        {
            for (int j = 0; j < parent.colLength; j++)
            {
                Console.WriteLine(i + "   " + j);
                cells[i, j].Size = new Vector2f(10, 10);
                cells[i, j].Origin = new Vector2f(0, 0);
                cells[i, j].Position = new Vector2f(i * 10, j * 10);
                cells[i, j].FillColor = Color.White;
            }
        }
MachCoyote
  • 11
  • 4
  • 1
    `cells[i, j]` is null... you need to `cells[i, j] = new RectangleShape();` after `Console.WriteLine(i + " " + j);` – Chetan Aug 13 '21 at 08:28
  • @Chetan ahh I see, thank you. I'm kinda new to this and would have assumed it wasn't null because of the already existing `= new RectangleShape[parent.rowLength, parent.colLength];` – MachCoyote Aug 13 '21 at 08:33
  • `new RectangleShape[` is an array.. .not a single object.. an array is used for storing multiple objects of the same types.. but it does not created objects in them... the objects needs to be created explicitly. – Chetan Aug 13 '21 at 08:36
  • @MachCoyote essentially you told the program to give you 10 buckets. But you never said what to put *into* those buckets. Then you said, get me the content of bucket number 2 and the program essentially said: "There is nothing in there, mate!" – MrPaulch Aug 13 '21 at 09:12
  • [Use your debugger](https://idownvotedbecau.se/nodebugging/) to inspect `cells`. – Dour High Arch Sep 03 '21 at 00:12

0 Answers0