Help! Object reference error!

J

Joey Johnson

I'm used to Java and am new to C#! I'm getting the following error, which
I believe is suggesting my code is referencing something that has not
been instanciated yet, however I can't seem to spot the bug...

"Object reference not set to an instance of an object"

What I'm TRYING to do is declare a publicly accessible class instance in
MAIN. Then other classes would create a reference to the MAIN class's
instance. My actual code snippets are:

----- FormMain.cs -----
public class FormMain : System.Windows.Forms.Form
{
...
public static FormMain formMain = new FormMain();
public DataHandler dispatcher = new DataHandler();

static void Main()
{
formMain.initializeData();
Application.Run(formMain);
}
...
}

----- DataHandler.cs -----
public class DataHandler : System.Windows.Forms.Form
{
...
public DataHandler dispatcher = FormMain.formMain.dispatcher;
...

dispatcher.setDay("Sunday");
...
}


Although this creates an error, getting rid of the 2 lines and above and
replacing them with this, works:

FormMain.formMain.dispatcher.setDay("Sunday");

Why!? What the heck is the difference and is there a workaround to get my
original code to work!?

-Joey
 
J

Joey Johnson

Sorry, that second class should have read this: (I'm sure it would've been
a circular reference error otherwise. :)


----- DeadHeader.cs -----
public class DataHeader : System.Windows.Forms.Form
{
...
public DataHandler dispatcher = FormMain.formMain.dispatcher;
...

dispatcher.setDay("Sunday");
...
}
 
J

Jon Skeet [C# MVP]

Joey Johnson said:
I'm used to Java and am new to C#!

Irrelevant in this case - you'd have got an NPE in Java too.

Although this creates an error, getting rid of the 2 lines and above and
replacing them with this, works:

FormMain.formMain.dispatcher.setDay("Sunday");

Within the constructor of DataHandler (or DataHeader - it's not too
clear from your two posts, to be honest)? That seems unlikely.
Why!? What the heck is the difference and is there a workaround to get my
original code to work!?

Look at the order of what happens:

A new instance of FormMain is created
FormMain.formMain is set to a reference to the instance
A new instance of DataHandler is created, which involves...
... looking at FormMain.formMain.dispatcher

- which hasn't been set yet! (It would be set *after* the constructor
returns.)

I believe this is the problem - but it's hard to say without a short
but *complete* program. See
http://www.pobox.com/~skeet/csharp/complete.html for what I mean by
that. If you don't understand after reading the above, post a complete
program (no need for it to be a GUI) and I'll walk you through it line
by line.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top