Object reference not set to an instance of an object

I have a Cell class:

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; }
}

Then I will 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());
                ///////////////////////////////////////////////////////

            }
        }
    }
}

In the end, the reference to Object is not set to the instance of the object (between ///// in the code above ..

I tried to create one instance of Cell, and it works great.

+5
source share
4 answers

When creating an instance of an array, the elements in the array get the default value for this type. So for

T[] array = new T[length];

, i 0 <= i < length array[i] = default(T). , array[i] null. NullReferenceException. Cell ,

HomeArray = new Cell [MAXCOL, MAXROW]; 

, , Cell, Cell. " , Cell s", " , Cell Cell." , null. HomeArray:

for (int i = 0; i < MAXCOL; i++)  { 
    for (int j = 0; j < MAXROW; j++)  { 
        HomeArray[i, j] = new Cell();
    } 
}
+12

.

public NietzscheBattleshipsGameModel()
{
    HomeArray = new Cell[MAXCOL, MAXROW];
    AwayArray = new Cell[MAXCOL, MAXROW];

    for (int i = 0; i < MAXROW; i++)
    {
        for (int j = 0; j < MAXCOL; j++)
        {
            HomeArray[i,j] = new Cell();
            AwayArray[i,j] = new Cell();
        }
    }
}
+4

. , HomeArray[i,j] null, , HomeArray[i,j].currentCell null.

UPDATE: , , , , .

, :

MessageBox.Show(HomeArray[i,j].currentCell.ToString());

HomeArray[i,j], HomeArray[i,j].currentCell NullReferenceException - , . , :

Cell cell = HomeArray[i,j].currentCell;
MessageBox.Show(cell.ToString());

, HomeArray[i,j] null, NullReferenceException , cell null, .

+3
source

You get an exception because you are not assigning a Cell instance to any of the slots in your matrices.

0
source

All Articles