How to declare an array of objects in C#

后端 未结 7 481
春和景丽
春和景丽 2020-12-23 16:12

I have a very beginning C# question. Suppose I have a class called GameObject, and I want to create an array of GameObject entities. I could think

7条回答
  •  醉话见心
    2020-12-23 16:36

    I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

    You need to initialize each member of the array separatedly.

    houses[0] = new GameObject(..);
    

    Only then can you access the object without compilation errors.

    So you can explicitly initalize the array:

    for (int i = 0; i < houses.Length; i++)
    {
        houses[i] = new GameObject();
    }
    

    or you can change GameObject to value type.

提交回复
热议问题