I have a class Cell:
public class Cell
{
public enum cellState
{
WATER,
SCAN,
SHIPUNIT,
SHOT,
HIT
}
public Cell()
{
currentCell = cellState.WATER;
MessageBox.Show(currentCell.ToString());
}
public cellState currentCell { get; set; }
}
I then try to use it in the following class:
public class NietzscheBattleshipsGameModel
{
private byte MAXCOL = 10;
private byte MAXROW = 10;
public Cell[,] HomeArray;
private Cell[,] AwayArray;
public NietzscheBattleshipsGameModel()
{
HomeArray = new Cell [MAXCOL, MAXROW];
AwayArray = new Cell [MAXCOL, MAXROW];
}
public string alphaCoords(Int32 x)
{
if (x < 0 || x > 9)
{
throw new ArgumentOutOfRangeException();
}
char alphaChar = (char)('A' + x);
return alphaChar.ToString();
}
public void test()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
// Object reference not set to an instance of an object.
MessageBox.Show(HomeArray[i,j].currentCell.ToString());
///////////////////////////////////////////////////////
}
}
}
}
I end up with the Object reference not set to an instance of an object (between the ///// in the above code..
I have tried creating a single instance of Cell and it works fine.
When you instantiate an array, the items in the array receive the default value for that type. Thus for
it is the case that for every
iwith0 <= i < lengthwe havearray[i] = default(T). Thus, for reference typesarray[i]will benull. This is why you are seeing theNullReferenceException. In your caseCellis a reference type so since you haveand all you have done is establish an array of references to
Cells but you never assigned those references to instances ofCell. That is, you told the compiler “give me an array that can hold references toCells” but you did not tell the compiler “give me an array that can hold references toCells and assign each of those references to a new instance ofCell.” Thus, the compiler will set the initial value of those references tonull. Therefore you need to initialize theHomeArray: