If I create a winForms "myForm" then the following boiler plate code is generated:
public partial class myForm: Form
{
public myForm()
{
//<<position 1
InitializeComponent();
//<<position 2
}
}
If I add extra code to the constructor method does it make any difference to the running of the app if I place my code in position 1 or 2 ?
Yes, it does.
InitializeComponent
is the method that VS generates that is responsible for creating and positioning the controls on a form.
Code in "position 1" will execute before the controls exist. If you try to access a control in this position, you'll get a NullReferenceException
(say, if you try to set the content of a TextBox
). Similar code in "position 2" will work as expected.
There is use to "position 1" though: if you have custom controls or behaviour that rely on properties of your form, setting those properties in "position 1" might prevent that code from having to refresh if you allow controls to be created before those values are set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With