|
-
Dec 12th, 2006, 05:37 PM
#1
Thread Starter
Member
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.
Using: VB.net + C#.net 2005 Express Editions + .Net Framework 2.0
~ Man Is The Warmest Place To Hide ~
-
Dec 12th, 2006, 06:33 PM
#2
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.
-
Dec 12th, 2006, 07:09 PM
#3
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.
VB/Office Guru™ (AKA: Gangsta Yoda™ ®)
I dont answer coding questions via PM. Please post a thread in the appropriate forum. 
Microsoft MVP 2006-2011
Office Development FAQ (C#, VB.NET, VB 6, VBA)
Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
If a post has helped you then Please Rate it! 
• Reps & Rating Posts • VS.NET on Vista • Multiple .NET Framework Versions • Office Primary Interop Assemblies • VB/Office Guru™ Word SpellChecker™.NET • VB/Office Guru™ Word SpellChecker™ VB6 • VB.NET Attributes Ex. • Outlook Global Address List • API Viewer utility • .NET API Viewer Utility •
System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6 
-
Dec 13th, 2006, 04:14 PM
#4
Thread Starter
Member
Re: Where should code be placed?
Thanks folks, I've taken note of what you've both said for future reference.
Using: VB.net + C#.net 2005 Express Editions + .Net Framework 2.0
~ Man Is The Warmest Place To Hide ~
-
Dec 14th, 2006, 05:46 PM
#5
Addicted Member
Re: Where should code be placed?
 Originally Posted by The Thing
Thanks folks, I've taken note of what you've both said for future reference. 
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|