473,608 Members | 2,565 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 "InitializeComp onent()" 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
InitializeCompo nent!
InitializeCompo nent();

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

// stuff deleted

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

//end

If you place the variable (instantiated object) myClass001 after
"InitializeComp onent()" 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.Some MemberFunction( ) = null, and you'll get a run-time
exception. Placing the instantiation of myClass001 = new Class001();
before InitializeCompo nent(); 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 1631
raylopez99 <ra********@yah oo.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 "InitializeComp onent()" 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.
InitializeCompo nent() 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
InitializeCompo nent 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.Threadin g;

class ConsoleApp
{
string name;
Timer timer;

public ConsoleApp()
{
InitializeSomet hing();
name = "Jon";
}

void InitializeSomet hing()
{
timer = new Timer(DisplayNa meLength);
timer.Change(50 0, Timeout.Infinit e);
// Wait for the timer to fire...
Thread.Sleep(10 00);
}

void DisplayNameLeng th(object state)
{
Console.WriteLi ne ("The length of the name is... {0}",
name.Length);
}
}

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

--
Jon Skeet - <sk***@pobox.co m>
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.co mwrote:

[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 InitializeCompo nent();

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********@yah oo.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 InitializeCompo nent();

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.co m>
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
2394
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 relevant announcements. If you're interested, drop me a note. But if for some reason you think that this discussion is fine here at the c.l.py, please let me know. ** LONG POST AHEAD **
5
3327
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 I'm adding a customer. The Customer fields are mostly foreign keys that refer to primary keys in other tables, left join instead of junction tables at this point. So, when I want to add a customer record, I also need to add records to the other...
4
1939
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 clarify with some ASCII art. Imagine a GraphicsPath describing a 4x4 pixel square with rounded corners (X = pixel, _ = blank) _ X X _ X X X X X X X X
8
11227
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 server... file test.php --------------------------------------------------- <?php
5
3147
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 wrong. Most examples to get things started include something: using Microsoft.Office.Interop.Excel; or using Excel; or using Excel = Microsoft.Office.Interop.Excel;
98
4551
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
2049
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 anyone else had this sort of problem with javascript? and any ideas how to fix it would be greatly appreciated.. I have included a copy of the code below, thanks. /**
3
6216
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 has to tell then them its wrong information but currently it takes then to a next page and then tells them its incorrect information. This is tedious as every time they enter wrong they will be redirected to a different page and then they have to...
97
2715
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 Reviews (2008 Jan 10) by Stephen Wolfram http://blog.wolfram.com/2008/01/10/ten-thousand-hours-of-design-reviews/ The issue is fitting here today, in our discussion of “closure” terminology recently, as well the jargons “lisp 1 vs lisp2”...
0
8057
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8470
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8329
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6813
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 projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6010
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3959
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2472
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1580
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1327
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.