Search code examples
c#arraysinstantiation

Initialize array of a class with fixed length and dynamically add values in C#


I want to have a two-dimensional game board, and every field is a custom class with information about this field, with properties. The size of the game board is known on instantiation, the values of the properties are not. After instantiation, I want to randomly set them for each field. My initial idea was to create an array, not a list, because the size of the game board is always fixed.

public class GameBoard
{
    private int _xValue;
    private int _yValue;
    private int _bombs;

    private int _fields;

    public Field[][] gameBoard;

    public GameBoard(int x, int y)
    {
        _xValue = x;
        _yValue = y;
        _fields = _xValue * _yValue;

        gameBoard = new[] { new Field[_xValue], new Field[_yValue] };
    //Here I have to initialize every Field

        for (int i = 0; i < _xValue; i++)
        {
            for (int j = 0; j < _yValue; j++)
            {
                //Set properties of Field
                //For example: gameBoard[i][j].IsBomb = RandomBoolean;
                //Here I get NullReferenceExceptions
            }
        }
    }
}

I do understand why this does not work. I tried lists, two-dimensional arrays or, like at the moment, a jagged array, what I would prefer. How can I solve this problem in a readable, clean way?

EDIT

The Field class:

public class Field
{
    public bool IsBomb { get; set; }
    public bool IsFlagged { get; set; }
}

I tried to add gameBoard[i][j] = new Field(); inside the nested forloop. This leads to an IndexOutOfRangeException.


Solution

  • Lots of confusion in here on how to work with jagged arrays. If you want to work with jagged arrays, you have to setup in such a way

    //Declare jagged array, I want _xValue arrays
    Field[][] gameBoard = new Field[_xValue][];
    
    for (int i = 0; i < _xValue; i++)
    {
        gameBoard[i] = new Field[_yValue];
        for (int j = 0; j < _yValue; j++)
        {
            gameBoard[i][j] = new Field(){ IsBomb = RandomBoolean};
        }
    }
    

    The equivalent in a multi-dimensional array would be

    //Declare multi-dimensional array of size _xValue x _yValue
    Field[,] gameBoard2 = new Field[_xValue, _yValue];
    
    for(int i = 0; i < _xValue; i++)
    {
        for(int j = 0; j < _yValue; j++)
        {
            // Instantiate the Field object at x,y
            gameBoard2[i, j] = new Field { IsBomb = RandomBoolean };
        }
    }