Neomex
Neomex

Reputation: 1660

Error at initialising array variables

I am pretty sure that I have initialised everything, but it still throws

"Object reference not set to an instance of an object."

    Cell[,] cell;
    bool[,] UpdateCell;

    int AreaSizeX;
    int AreaSizeY;
    int MaxAge;

    public void Reset(int areaSizeX, int areaSizeY, int maxAge)
    {
        AreaSizeX = areaSizeX;
        AreaSizeY = areaSizeY;
        MaxAge = maxAge;

        cell = new Cell[AreaSizeX, AreaSizeY];
        UpdateCell = new bool[AreaSizeX, AreaSizeY];

        for (int i = 0; i < areaSizeX; i++)
        {
            for (int j = 0; j < areaSizeY; j++)
            {
                cell[i, j].Alive = false; //throws exception here #########
                cell[i, j].Age = 0;

                UpdateCell[i, j] = false;
            }
        }
    }

What is wrong in this code? C# does not allow dynamic array creation?

Upvotes: 1

Views: 68

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500665

I assume Cell is a class (a reference type). That means the elements of the array are references. You're creating an array, but all the elements will be null by default -. You probably want:

for (int i = 0; i < areaSizeX; i++)
{
    for (int j = 0; j < areaSizeY; j++)
    {
        cell[i, j] = new Cell();
        cell[i, j].Alive = false;
        cell[i, j].Age = 0;

        UpdateCell[i, j] = false;
    }
}

Or you could give your Cell class a constructor taking the age and liveness:

for (int i = 0; i < areaSizeX; i++)
{
    for (int j = 0; j < areaSizeY; j++)
    {
        cell[i, j] = new Cell(false, 0);
        UpdateCell[i, j] = false;
    }
}

Or use an object initializer to set the properties:

for (int i = 0; i < areaSizeX; i++)
{
    for (int j = 0; j < areaSizeY; j++)
    {
        cell[i, j] = new Cell { Alive = false, Age = 0};
        UpdateCell[i, j] = false;
    }
}

Upvotes: 4

Related Questions