1

I'm trying to create a 2D array of objects (basically an XY coordinate system), but I'm not sure how. I have a Map class which creates Tile objects. In the constructor for the Map class, I have written code to create a 2D jagged array of Tile objects.

I'm not sure why this isn't working, previously I had created 2D jagged arrays of integers and that was working fine.

What's causing the error and how should I be trying to create the array of objects?

This is the error I'm getting:

Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
   at ObjectArray.Map..ctor(Int32 NumberOfRows, Int32 NumberOfColumns) in C:\Use
rs\Lloyd\documents\visual studio 2010\Projects\ObjectArray\ObjectArray\Map.cs:li
ne 27
   at ObjectArray.Program.Main(String[] args) in C:\Users\Lloyd\documents\visual
 studio 2010\Projects\ObjectArray\ObjectArray\Program.cs:line 18

My Tile.cs

class Tile
{
    public int TileID { get; set; }

}

And my Map.cs:

class Map
{
    private Tile[][] TileGrid;

    public int Columns { get; private set; }
    public int Rows { get; private set; }

    public Map(int NumberOfRows, int NumberOfColumns)
    {
        Rows = NumberOfRows;
        Columns = NumberOfColumns;


        TileGrid = new Tile[NumberOfRows][];
        for (int x = 0; x < TileGrid.Length; x++)
        {
            TileGrid[x] = new Tile[NumberOfColumns];
        }

        //Test for the right value.
        TileGrid[0][0].TileID = 5;
        Console.WriteLine(TileGrid[0][0].TileID);

    }
}

2 Answers 2

5

This line

TileGrid[x] = new Tile[NumberOfColumns];

creates an array of null references of the given length. So you need to iterate over it and initialize each reference with an object:

TileGrid = new Tile[NumberOfRows][];
for (int x = 0; x < TileGrid.Length; x++)
{
    TileGrid[x] = new Tile[NumberOfColumns];
    for (int y = 0; y < TileGrid[x].Length; y++)
    {
        TileGrid[x][y] = new Tile();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Before you can use an element you must make a new one... like this:

TileGrid[0][0] = new Tile();

Then you can use it:

TileGrid[0][0].TileID = 5;

The error messages is exactly true, you were trying to reference a null Tile location.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.