0

In the first picture is my parent class:

enter image description here

All it does is set header to "default header" and make new array of type LevelData. When I call Setup(), the overridden child method is called as I want it to. In the child class on Setup() method when I print header it says "default header" as should. When I print length of the array it says 10 as it should.

But when I try to access the array I get an Object reference error. Why can I access the header and the length of the array but not the array itself?

Here is the child:

enter image description here

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Jonathan
  • 325
  • 2
  • 3
  • 24

1 Answers1

2

When you create an array, all array elements are initialized to default(T) where T is the element type. For reference types (a class is a reference type), this is always null. string is a reference type as well. For numeric types default(T) is always the value 0. All other types are initialized with all bits set to 0.

If you want the array to contain elements, you must initialize each entry:

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

Note that a class might not have a default constructor, i.e. a constructor with no parameters. A class might have no public constructor at all and be instantiatable only through a factory method. How should the array be initialized automatically with non null entries then?

See: Arrays (C# Programming Guide)

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188