Where should InitializeComponent() appear in code order?
c#, visual-studio-2010, winforms
Solution
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.
Problem
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 ?