Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should InitializeComponent() appear in code order?

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 ?

like image 647
whytheq Avatar asked Aug 15 '12 08:08

whytheq


Video Answer


1 Answers

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.

like image 70
Dan Puzey Avatar answered Oct 19 '22 07:10

Dan Puzey