2

I have two classes:

public class SubObject {
    public int id;
}

public class Object {
    public SubObject[] SubObjects;
}

And I have one array:

public Object[] Objects;

When I try to instantiate this array:

public void InstantiateArrays(int objectsSize, int subObjectsSize) {
    Objects = new Object[objectsSize];
    foreach (Object obj in Objects) {
        obj.SubObjects = new SubObject[subObjectsSize];
    }
}

I am receiving this error:

An exception of type 'System.NullReferenceException' occurred in **** but was not handled in user code

Additional information: Object reference not set to an instance of an object.

dngadelha
  • 1,314
  • 2
  • 11
  • 14

2 Answers2

1

This is invalid:

Objects = new Object[objectsSize];
foreach (Object obj in Objects) {

this is because the first line will create an array that consists of null references, which is the default value of an Object reference in C#. Using foreach does not let you overwrite references.

You need to use array indexes to set array elements:

for(int i = 0; i < this.Objects.Length; i++ ) {
    this.Objects[i] = new SubObject[ subObjectSize ];
}

Note that using Object is generally a bad idea as it forces you to use casting. If you have a tiered object hiearchy then use strong typing or better yet: generics, where appropriate.

Dai
  • 141,631
  • 28
  • 261
  • 374
1

In this line:

Objects = new Object[objectsSize];

You create an array. The elements of the array are initialized to the default values for the type. Since it's an array of objects, this default value is null.

Within the loop, you're trying to access the field SubObjects of an object that's null:

obj.SubObjects = new SubObject[objectsSize];

A quick fix is to use a for loop and instantiate the objects in your loop:

for (int i = 0; i < subObjectSize; i++)
{
    Objects[i] = new Object();
    Objects[i].SubObjects = new SubObject[subObjectsSize];
}

Also note that naming one of your classes Object is bad practice, since this is the name of the class at the root of the object heirarchy.

pb2q
  • 58,613
  • 19
  • 146
  • 147