Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference not set to an instance of an object

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.

like image 737
iTEgg Avatar asked Feb 04 '10 18:02

iTEgg


People also ask

How do you fix the object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

How do I fix this error object reference not set to an instance of an object in unity?

Common solution:Check if your variable is attached to the object in question (you can find more clues in the other error lines). You might destroy the object before you use it. Check if it's the case. You might start the coroutine before you define the variable.

How do I fix NullReferenceException in C#?

Solutions to fix the NullReferenceException To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. In the above example, if(cities == null) checks whether the cities object is null or not.


3 Answers

When you instantiate an array, the items in the array receive the default value for that type. Thus for

T[] array = new T[length];

it is the case that for every i with 0 <= i < length we have array[i] = default(T). Thus, for reference types array[i] will be null. This is why you are seeing the NullReferenceException. In your case Cell is a reference type so since you have

HomeArray = new Cell [MAXCOL, MAXROW]; 

and all you have done is establish an array of references to Cells but you never assigned those references to instances of Cell. That is, you told the compiler "give me an array that can hold references to Cells" but you did not tell the compiler "give me an array that can hold references to Cells and assign each of those references to a new instance of Cell." Thus, the compiler will set the initial value of those references to null. Therefore you need to initialize the HomeArray:

for (int i = 0; i < MAXCOL; i++)  { 
    for (int j = 0; j < MAXROW; j++)  { 
        HomeArray[i, j] = new Cell();
    } 
}
like image 102
jason Avatar answered Sep 28 '22 08:09

jason


You need to initialize the Cells in your arrays.

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();
        }
    }
}
like image 31
Austin Salonen Avatar answered Sep 28 '22 07:09

Austin Salonen


Arrays are initialised to be empty - the Null reference is because HomeArray[i,j] is null, not because HomeArray[i,j].currentCell is null.

UPDATE: If you have a statement where a couple of different things could be null, then I generally split that up into multiple lines to make it easier to tell what is null.

For example, in your case:

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

Either HomeArray[i,j] or HomeArray[i,j].currentCell could potentially be null and trigger a NullReferenceException - there is no way to tell which it was from the exception. If you split that statement up however:

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

In this case if HomeArray[i,j] is null then you get your NullReferenceException on the first, line whereas if cell is null you get it on the second line.

like image 42
Justin Avatar answered Sep 28 '22 09:09

Justin