Where should code be placed?
Hi folks, I'm wondering if it's bad practice in Visual C# to have code in the constructor like so
Code:
public Form1()
{
InitializeComponent();
//Some user generated code here like the examples below
method1();
method2();
etc, etc.....
}
or is it better to have methods called, variables declared, etc, in the app's
Form1_Load(...){.....} portion of the code as any code here will run when the form loads anyway.
Thanks for your help. :thumb:
Re: Where should code be placed?
Microsoft recommend placing as little code as possible in a constructor. I would suggest any simple initialisation be done in the constructor but anything remotely complex, like getting data from any external source, be done in the Load event handler.
Re: Where should code be placed?
Also, anything you place in there should be more related to the presentation or creation of the form vs. obtaining external data or such.
Re: Where should code be placed?
Thanks folks, I've taken note of what you've both said for future reference. :thumb:
Re: Where should code be placed?
Quote:
Originally Posted by The Thing
Thanks folks, I've taken note of what you've both said for future reference. :thumb:
The main purpose of a constructor is to initialize the state of the object. Anything your form needs for this purpose is appropriate to place in the constructor. However, there are a number of things you can't do with the form in the construtor, like setting focus on a control, so you will want to familiarize yourself with what can be done. A little experimentation might be helpful.