Initialize properties on load event or constructor?

I have a property that refers to a service layer object and I need it every time I use the form. What's the best estimate: initialize the property in the constructor or on the form load event?

+2


source to share


5 answers


If the validity of the form state depends on a set property, then set the property in the constructor. You always want your objects to be in the correct state after creating them.



+3


source


Yes, but be careful what you do in the form designer, as the visual designer will trigger this when you open the form for editing.

If you put something here that relies on other things that are configured at runtime, it might throw an error and you won't be able to edit the form's layout.



I would say putting it in the Load form for this reason.

+2


source


In the constructor. Very often you are new to a form and you need to set some properties or make other settings before you can actually show the form. In these cases, you want all of your instance variables to be set up even before the Form actually loads.

0


source


The constructor should be responsible for initialization unless you have a specific need or dependency to initialize your variable in Load Load, such as initializing it to something that depends on something else.

0


source


You must initialize properties in the constructor. The constructor is obviously only called once per form instance. The load event handler will be called every time the form is displayed. Also, if you've done an initialization operation, such as populate a combo box, in a load event handler, you need to write some rather hoarse code to preselect a value in that combo box before displaying the form. This is just one example. Hope it helps.

0


source







All Articles