473,384 Members | 1,854 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,384 software developers and data experts.

The importance of the right 'entry point' when adding your class inC# Form constructor

Oh, I know, I should have provided complete code in console mode
form. But for the rest of you (sorry Jon, just kidding) I have an
example of why, once again, you must pick the correct entry point in
your code when adding a class (oops, I meant variable, or
instantiation of a object that's a class) to a form constructor.

Specifically, adding a class variable should always come BEFORE the
statement "InitializeComponent()" in your form constructor.

Consider this example (WRONG WAY):

public partial class Form2 : Form
{
Class001 MyClass001; //must be declared here--but that's not
the point of this thread

public Form2()
{

//myClass001 = new Class001(); // MUST BE PUT HERE, BEFORE
InitializeComponent!
InitializeComponent();

myClass001 = new Class001(); //WRONG! DO NOT PLACE
AFTER! GET RUNTIME ERROR!
}

// stuff deleted

private void splitContainer1_Panel1_Resize(object sender, EventArgs e)
{
myClass001.SomeMemberFunction(); //RUN-TIME ERROR! THIS IS
NULL SINCE myClass001 DOES NOT EXIST!!!
}

//end

If you place the variable (instantiated object) myClass001 after
"InitializeComponent()" the program will likely not work, because the
splitContainer control object actually gets fired up or instantiated
*before* the Form2 (subform to Form 1) default constructor does.
Don't ask me why, but that's what happens. Hence
myClass001.SomeMemberFunction() = null, and you'll get a run-time
exception. Placing the instantiation of myClass001 = new Class001();
before InitializeComponent(); however, solves this problem.

Another example of having to correctly pick the right 'entry point'
for something.

And btw you won't find this error in "Console Mode". Sorry Jon! ;-)

RL
Aug 1 '08 #1
3 1617
raylopez99 <ra********@yahoo.comwrote:
Oh, I know, I should have provided complete code in console mode
form. But for the rest of you (sorry Jon, just kidding) I have an
example of why, once again, you must pick the correct entry point in
your code when adding a class (oops, I meant variable, or
instantiation of a object that's a class) to a form constructor.

Specifically, adding a class variable should always come BEFORE the
statement "InitializeComponent()" in your form constructor.
That's true if any of the events which get fired during initialization
rely on that variable, yes.
Another example of having to correctly pick the right 'entry point'
for something.

And btw you won't find this error in "Console Mode". Sorry Jon! ;-)
You can see exactly the same effect in a console app.
InitializeComponent() tends to do more than you'd do in a non-GUI
constructor, particularly around firing events, but there's nothing
GUI-specific going on in terms of the language here. It's just that
InitializeComponent happens to fire some events after subscribing to
them.

Here's an example of a console app which similarly dies (although on a
threadpool thread, so the process just gets torn down):

using System;
using System.Threading;

class ConsoleApp
{
string name;
Timer timer;

public ConsoleApp()
{
InitializeSomething();
name = "Jon";
}

void InitializeSomething()
{
timer = new Timer(DisplayNameLength);
timer.Change(500, Timeout.Infinite);
// Wait for the timer to fire...
Thread.Sleep(1000);
}

void DisplayNameLength(object state)
{
Console.WriteLine ("The length of the name is... {0}",
name.Length);
}
}

class Program
{
static void Main()
{
new ConsoleApp();
}
}

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Aug 1 '08 #2
On Aug 1, 3:02*pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:

[stuff about console mode]

Thanks Jon. What I found strange was that a split container would get
initialized /worked on by the compiler/interpreter/runtime engine
before the form that contains the split container. That was
unexpected. To get around this problem, I simply moved the variable
that I needed before the statement InitializeComponent();

To me it shows that you have to be careful where you insert your
classes...but that's too general a statement to be of much use, I
admit.

RL
Aug 2 '08 #3
raylopez99 <ra********@yahoo.comwrote:
[stuff about console mode]

Thanks Jon. What I found strange was that a split container would get
initialized /worked on by the compiler/interpreter/runtime engine
before the form that contains the split container. That was
unexpected. To get around this problem, I simply moved the variable
that I needed before the statement InitializeComponent();

To me it shows that you have to be careful where you insert your
classes...but that's too general a statement to be of much use, I
admit.
Note that this isn't a matter of where the variable is *declared* -
it's where it's *initialized*. The location of the variable declaration
doesn't make much difference (in 99.9% of cases, anyway - there are
some edge cases which should be avoided) but if you're going to assume
that the variable contains a useful value, you'd better make sure that
value has been set before you try to use it.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Aug 2 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Carlos Ribeiro | last post by:
Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and...
5
by: Ross A. Finlayson | last post by:
Hi, I'm scratching together an Access database. The development box is Office 95, the deployment box Office 2003. So anyways I am griping about forms and global variables. Say for example...
4
by: Don | last post by:
When creating a new region for a control via a GraphicsPath object, it appears the entire rightmost column of pixels and bottom most row of pixels are not included in the region. I will try to...
8
by: julian_m | last post by:
I'm having problems with include. I wrote a small example which shows what's going on... I should say that the problems started after I moved to a shared server. All was working fine in my local...
5
by: Mike in Santa Rosa | last post by:
I'm trying to get a simple c# app built that can launch/manipulate an excel workbook, sheet. I've chased down several examples and can't any of them to work. So I must be doing somethnig obviouslt...
98
by: tjb | last post by:
I often see code like this: /// <summary> /// Removes a node. /// </summary> /// <param name="node">The node to remove.</param> public void RemoveNode(Node node) { <...> }
1
by: DJG79 | last post by:
Hi all, I am using an open source menu that i found and it works great, except for one thing that when the web page is not scrolled to the very top the drop down links will not stay visible. Has...
3
by: satishknight | last post by:
Hi, Can some one tell me how to change the validation sequence for the code pasted below, actually what I want it when any one enters the wrong login information (already registered users) then it...
97
by: xahlee | last post by:
I'd like to introduce a blog post by Stephen Wolfram, on the design process of Mathematica. In particular, he touches on the importance of naming of functions. • Ten Thousand Hours of Design...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.