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.
Fieldis aclassthen aftergameBoard = new[] { new Field[_xValue], new Field[_yValue] };you have a jagged array ofnulls - you need tonewthem in your loopgameBoard[i][j] = new Field();, in the nested for loop. Then I get: IndexOutOfRangeExceptionListand convert it toArrayafter adding an itemsListat all? There is no need.