Where to put Constructor Code?

  • Thread starter Thread starter Keith Smith
  • Start date Start date
K

Keith Smith

Does it make more sense to put additional constructor code WITHIN the
InitializeComponent(); method? Or should I put it right after the
InitializeComponent(); is called (in the public Form1() method)?
 
Keith said:
Does it make more sense to put additional constructor code WITHIN the
InitializeComponent(); method? Or should I put it right after the
InitializeComponent(); is called (in the public Form1() method)?

Well the InitializeComponent method is where the designer generated code
is placed. Although you can certainly add/change it if you want, if
there is no need to I would keep my own code out of there. You can place
your own constructor code before or after the call as long as you
realize that the designer generated code has to be executed before your
gui elements are initialized. So you would probably end up with
something like:

public Form1() {
//Ctor code that needs to be run before anything else
//InitializeComponent()
//Ctor code that needs to work with gui objects
}
 
Keith Smith said:
Does it make more sense to put additional constructor code WITHIN the
InitializeComponent(); method? Or should I put it right after the
InitializeComponent(); is called (in the public Form1() method)?

public MyClass():System.Windows.Forms.Form.Form
{
public MyClass()
{
InitializeComponent();
initializeSomeMore();
}

// ...

initializeSomeMore();
{
// more initializing
}

private void MyClass_Load(object sender, System.EventArgs e)
{
// more initializing
}
}
 
Hi Keith,

I don't think you should put the code in InitializeComponent() method since
it is generated by desinger. Instead you could put your after/before the
InitializeComponent() call in ctor.
 
Back
Top