Do you have a class that has an object property that needs to be initialized or instantiated? You can always instantiate the property in the Constructor (or Open event) like this:
MyClass1 = New MyClass
But you can also do this using a Computed Property on a Class (I’m using TestClass for this example).
First, create a private property such as mMyClass1 As MyClass. It will be Nil by default as all object properties are.
Then create a Computed Property called MyClass1 As MyClass.
In the Get, check if mMyClass1 is Nil. If it is, create it. Then return it.
If mMyClass1 Is Nil Then
mMyClass1 = New MyClass
End If
Return mMyClass1
Most likely you’d want this property to be read-only so you would not implement Set (even though the property is read-only, since it is an object you’ll still be able to modify the properties it contains). But if you did want a way for the object reference to be changed, you can do this in the Set:
mMyClass1 = value
Now you can make use of MyClass1 on TestClass as shown below. The above technique has two advantages over instantiating the property in the Constructor:
- It keeps the code more closely associated with the property.
- The property is only initialized when it is first accessed.
Var tc As New TestClass tc.MyClass1.TestNumProperty = 42
This technique is also referred to as Lazy Loading or Lazy Initialization.