473,395 Members | 2,467 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,395 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 1619
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.