1

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?

1 Answer 1

4

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh look how fast he answered!

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.