-4

I have four classes:
PointMass, which inherits from PropPhysics, which inherits from Entity (PropPhysics and Entity are both abstract classes), and World which has a List<Entity> called Entities.

Here, I'm trying to add a PointMass to a World's List<Entity>.

Strangely, whenever I try to add a new, globally defined, or even existing PointMass (within the method's scope), I get a "NullReferenceException was unhandled" error.

I check whether, or not, the PointMass "pMass" is null, but it is not, and it raises the same error.

I even display a message box whenever a PointMass is constructed, but it still raises the same error.

No luck was found from other research.

    private void Display_Click(object sender, EventArgs e)
    {
        p.PositionX = 0;
        p.PositionY = 0;
        p.Mass = 5;

        PointMass pMass = new PointMass();
        if (pMass==null)
        {            
            MessageBox.Show("error: Mass is null");
        }

        MyWorld.Entities.Add(new PointMass());
        MyWorld.Entities.Add(pMass);
        MyWorld.Entities.Add(p); 
    }
akuzma
  • 1,592
  • 6
  • 22
  • 49
  • 5
    It's not strange. Chances are `MyWorld` is null or `MyWorld.Entities` is null. -1: *please use the debugger to remove "Strange" from the equation* –  Jan 14 '13 at 08:37

2 Answers2

3

Most likely, you forgot to initialize p, MyWorld or MyWorld.Entities.

I assume the latter, so make sure you have code like this in the constructor of World:

Entities = new List<Entity>();

You can very easily find out which variable actually is null by using a Debugger. Please do so in the future before posting such a question.

BTW: pMass can't be null directly after it has been created.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

Try to initialize MyWorld.Entities or p in your code. Like;

Entities e = new List<Entity>();
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364