.net – Handling events fired in constructors

eventsvb.net

Work = New ExampleWork()  

Here the Work is a withevents variable and I've used the handles clause for handling various events fired by the ExampleWork object. However the event handler will not get assigned till the constructor of the ExampleWork returns. Now how can I handle any events fired from the constructor? I can move the constructor logic out to a separate method and call it after the constructor has returned and thus handle all the fired events including events fired from constructor. However it doesn't look good.
What is the best way to handle such a situation?

Best Answer

Ignoring the VB syntactic sugar for event handling, if an object is raising events on itself during its construction, that's a design smell. There are only two ways that those events could be subscribed:

  • The object could be exposing itself to the outside world while it's still being constructed, e.g. via a callback or static method call. This is generally a bad idea - if an object is still being constructed, it generally can't be considered to be "ready to use". In particular, there may still be a more-derived constructor body still to be called.

  • The object could be handling the events itself. This isn't quite so bad, but those event handlers still need to be aware that they're going to be called on a partially-constructed object.

Basically, try to avoid events being raised on an object during construction. Ideally, make the constructors themselves nice and simple, leaving the object in a valid initial state.