How to instantiate a nested Class

I always mess up instantiating Classes. Here I am trying to create a Class of TreeFormula that has within it, a Class of Trunks. When I run this, I am able to assign values to the simple members of TreeFormula (the colors) but the Trunk assignment fails with a NilObjectException. Do I need to instantiate the Trunks in some way? I tried TreeDNA.Trunk(3) = New Gobals.Trunks but that did not work either.

I have an image that shows my Class definitions and the code I am using as the App starts.

Thanks,

Any variable or property that is meant to hold an instance of a class must be instantiated before use. If you had done this, you’d get the same NilObjectException:

var t as Trunk
t.Prop = x

Instead, you’d do this:

var t as new Trunk
t.Prop = x

In this case, since it’s an array, the easiest thing to do is to create the array in the TreeFormulas’ Constructor:

Sub Constructor
  for index as integer = 0 to Trunk.LastIndex
    Trunk( index ) = new Trunks
  next
End Sub
1 Like

I did not understand that each instance of an array needed a separate declaration. I get it now. Thanks.

1 Like

Only because each instance of Trunks is an object. If your array had been an array of (say) integers, that would not be necessary. As it was you had an array of three Nil pointers unless you create the Trunks instances when you create the TreeFormula.