Null Reference Exception when calling an Object Array

耗尽温柔 提交于 2019-11-29 08:59:38

Your code should be

if (roomArray[i] != null)

Whenever you create an array, you'll have to initialize it's individual items before you can access them.

Room[] roomArray = new Room[20];

roomArray[0] = new Room();

Because the elements of Room inside Room[] we're not initialized.

Try

public Form1()
{
    InitializeComponent();
    for(int i = 0; i < roomyArray.Length; i++) roomArray[i] = new Room();
}
Stuart Blackler

As the other answers have said, you need to initialize the array before you start using it. When you write:

Room[] roomArray = new Room[20];

What you are telling the computer to do is reserve you enough memory for references to 20 objects of the type Room. The other solutions proposed are fine, but if you want performance, try the following:

According to this SO answer, using the following function would be more performant than the other solutions provided thus far. This also has supporting evidence from this blog post.

Note: I've converted to use generics

    /// <summary>
    /// Fills an array with a default value
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="array">The array to fill with a default value</param>
    /// <param name="value">The default value</param>
    public static void MemSet<T>(T[] array, T value)
    {
        if (array == null)
        {
            throw new ArgumentNullException("array");
        }

        int block = 32, index = 0;
        int length = Math.Min(block, array.Length);

        //Fill the initial array
        while (index < length)
        {
            array[index++] = value;
        }

        length = array.Length;
        while (index < length)
        {
            Buffer.BlockCopy(array, 0, array, index, Math.Min(block, length - index));
            index += block;
            block *= 2;
        }
    }

Usage

Memset<Room>(roomArray, new Room());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!