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