Shared Constructor

A class can also have a shared constructor:

shared sub New()

End sub

Normal constructors are called when an instance of the class is created. The shared constructor is called only once during the lifetime of an application, immediately before any use of the class.

This means that the shared constructor is called before any other shared methods, and before any instances of the class are created. The first time any code attempts to interact with any method on the class, or attempts to create an instance of the class, the shared constructor is invoked.

Because you never directly call the shared constructor, it cannot accept any parameters. Moreover, because it is a shared method, it can only interact with shared variables or other shared methods in the class.

Typically, a shared constructor is used to initialize shared fields within an object. In the Person class, for instance, you can use it to initialize the mCount variable:

shared sub New()

mCount = 0 End sub

Because this method is called only once during the lifetime of the application, it is safe to do one-time initializations of values in this constructor.

0 0

Post a comment