Monday, September 09, 2013

Winforms C# : Prefer initialization in constructor instead of Form_Load event handler

On Windows Forms, I have been doing initialization of values on Form_Load event handler. I use constructor mostly for make instances of member variables and setting basic/default values. I did the rest of the settings e.g: config, last state, on Form_Load. It turns out that it's not actually a best practice to do so.

I've just stumbled upon this discussion on Stack Overflow that explain that it is actually better to minimize the use of Load. In summary, here's the guideline on Constructor vs. Load issues :

  1. Initialize things on constructor 
  2. Only use Load for code that needs valid windows handle e.g: code that requires the window size and location to be known
  3. Override  OnLoad instead of using Form_Load event handler. This ensure more deterministic order of execution in relation to parents OnLoad call
I guess it's time to change the habit.

No comments: