Skip to content

Control Subclass Constructors

A constructor is a special method that is used to initialize a class. They are very handy, but when you use them with control subclasses you have to be aware of how a control’s properties are initialized. Perhaps you’ve run into this situation:

“I have a constructor on my control and the values that I set in the constructor don’t stick.”

But, indeed IF you put a break point in the constructor for your control subclass you will see it definitely gets called. And the values you set are present when the constructor is exited.

What most people miss is that if you made your public properties into computed ones and put a break point in the setter you’d find that this gets called AFTER the constructor.

And this is REALLY relevant.

Normally a control instance on a layout is created and configured using code much like:

  // the next line obviously calls the constructor
  dim c as Control = new <your custom control subclass name>

  // and IF you had a computed property and
  // set a break point in each computed property setter
  // you will see each setter get called in turn

  c.SetAllProperties( paramarray of property names and values )

and so the first calls to the setters are what put the values you set in the Inspector onto your control.

And this is what people do not usually expect.

But how else would you get all those properties onto the control and NOT require every control subclass to have a special constructor ?

Usually the advice is “put your set up code in the Open event” which is often too late.

IF you do set property values you want to keep in the constructor there are a few choices.

  1. Don’t make these properties “public” as every public property will be set in the “SetAllProperties” call. PER INSTANCE properties should be unique to that instance and so they all get set if they are public. Private and protected properties won’t.
  2. Make your public properties into computed properties and “skip” the first call to the setter so whatever value you set in the constructor does not get written over by the call to SetAllProperties.
  3. Make the properties public and set the initial values in the inspector (which is IMHO the “right” way to do this)

I’ve put together a sample you can put break points in to see that the constructor and setters for public properties are called exactly as described.