Problem instantiating class field to null

G

Guest

I have defined to classes like this:

namespace PanelColors.Helpers
{
public class PanelColor
{
public PanelColor()
{
r = 0; g = 0; b = 0;
}

public PanelColor(int red, int green, int blue)
{
r = red;
g = green;
b = blue;
}

public int R
{
get { return r; }
set { r = value; }
}

public int G
{
get { return g; }
set { g = value; }
}

public int B
{
get { return b; }
set { b = value; }
}

private int r, g, b;
}

public class PanelColorsArray
{
public PanelColor[] panelColors; // Declare an array of PanelColor

public PanelColorsArray()
{
panelColors = new PanelColor[] { cDay, cNight, cLuminous, cTemp };
panelColors.Initialize();
}

public void PanelColorsInit()
{
cDay.R = 255; cDay.G = 255; cDay.B = 255;
cNight.R = 10; cNight.G = 10; cNight.B = 10;
cLuminous.R = 40; cLuminous.G = 220; cLuminous.B = 20;
cTemp.R = 0; cTemp.G = 0; cTemp.B = 0;
}

public PanelColor cDay;
public PanelColor cNight;
public PanelColor cLuminous;
public PanelColor cTemp;
} // class: PanelColorsArray
} // namespace

In the code that uses them the cDay, cNight, cLuminous, and cTemp are NULL,
and do not point to fields within the class.

So, when I try to use them (and yes I know it is not encapsulated) like this
in the main code:

PanelColorsArray ourColors = new PanelColorsArray();
int curColor; // Point to day colors

ourColors.panelColors[0].R = ....

I get an unhandled exception of type 'System.NullReferenceException'
occurred in PanelColors.exe.

But I just don't get why when they are not getting instantiated by the
constructor.

Help.
 
B

Barry Kelly

Stick said:
I have defined to classes like this:

namespace PanelColors.Helpers
{
public class PanelColor
public PanelColor cDay;

Should probably be:
public PanelColor cDay = new PanelColor();
// ... etc.
In the code that uses them the cDay, cNight, cLuminous, and cTemp are NULL,
and do not point to fields within the class.

Yes, that's the expected behaviour.
But I just don't get why when they are not getting instantiated by the
constructor.

Classes are never instantiated unless you instantiate them yourself,
with a 'new' expression. It's not like C++; all classes are always on
the heap, and must always be ultimately allocated via 'new'.

-- Barry
 
G

Guest

I figured it out!

public PanelColor cDay;

needed to be:

public PanelColor cDay = new PanelColor(255, 255, 255);

Stick
 

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