Here’s a piece of code coming from a C# project using a 2d array. For a reason I don’t understand my program compiles perfectly but during run-time it crashes.
public class Tile_Info
{
public int id;
public Tile_Info(int _id)
{
id = _id;
}
}
class Program
{
public static void Main(string[] args)
{
int width = 20;
int height = 30;
Tile_Info[,] my_tile;
my_tile = new Tile_Info[width, height];
for(int y = 0; y < height; y++)
{
for(int x = 0; x < width; x++)
{
my_tile[x, y].id = 0;
}
}
}
}
According to the debugger it’s because “Object reference not set to an instance of an object”, but I’m pretty sure it’s what I’m doing here: my_tile = new Tile_Info[width, height];.
Anyone can tell what’s wrong? Thank you for your support!
The creation of the array does not create the objects themselves, just like a creation of a parking lot does not create the cars that park there.
You still need to create the objects yourself. Change
to
This only happens when reference types (
class) are used because the thing that is stored in the array is a reference to an instance, instead of the instance itself. On a lower level this (more or less) means that the memory for the instance is not yet allocated, just the memory for its reference, so you mustnewup an instance to initialize it. On the other hand ifTile_Infois a value type (struct) then the array will contain the actual instance, and thenew Tile_Info[width, height]would have initialized the allocated memory to valid start state (all zeroes), which is exactly what the default parameterless constructor of a value type does.So, if you had defined Tile_Info like this:
both
my_tile[x, y].id = 0andmy_tile[x, y] = new Tile_Info(0)would have been legal.