Initialize properties at the load event or in the constructor?
I have a property that references a service layer object and I need it every time I开发者_开发技巧 use a form. What is the best pratice: initialize a property in the constructor or in the form's load event?
If the validity of the state of the form is dependent upon the property being set, then set the property in the constructor. You always want your objects to be in a valid state after they're constructed.
Yeah, but be careful what you do in the constructor of a form, as the visual designer will run this when you open up the form to edit.
If you put anything here that relies on other stuff being set up at run time, it is likely to cause an error and you wont be able to edit the form layout.
I would say put it in the Form Load for this reason.
In the constructor. Very often you new up a form, and need to set some properties, or do other kind of set up before you actually display the form. In those cases, you'll want all your instance variables to be set up even before the Form actually loads up.
Constructor should be responsible for initialization, unless you have specific need or dependency to initialize your variable on Form Load, such as initializing it to something that is dependent on something else.
You should initialize properties in the constructor. The constructor is obviously called only once per form instance. The load event handler will be called every time a form is shown. Also, if you did initialization work, such as fill a combo box, in the load event handler, you'd have to write some pretty hacky code to preselect a value in that combo box before showing a form. That's just one example though. Hope that helps.
精彩评论