Where to put Constructor Code?

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)?
 
O

Olle de Zwart

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
}
 
P

Patrick

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
}
}
 
P

Peter Jausovec

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top