User
User

Reputation: 1488

Why would this give out a NullReferenceException?

I have a method caller addColisionBox and when i call it and setting values to it i get nullpointer at the place im calling it.. I will show some code:

    public void addCollisionBox(int x, int y, int arrayNum)
    {
        //Creating a new rectangle at the x & y cord passed in
        rectangle[arrayNum] = new Rectangle(x, y, R_Width, R_Height);
    }

And i created inside another class like this:

CollisionHandler collision;
....
//CurrentX and CurrentY position to pass into addCollisionBox method and at the array number i
collision.addCollisionBox(currentX, currentY, i);

And it says in a message box that Visual C# express give out that: "Object reference not set to an instance of an object."

Upvotes: 1

Views: 138

Answers (5)

Matt Lacey
Matt Lacey

Reputation: 8255

I would suggest that collision is null when you're trying to call the addCollisionBox method on it, thereby causing the null dereference. If it definitely has a value at some stage then you're probably deleting it somewhere, but given the code you've pasted it seems more likely that you just need to create an instance of CollisionHandler as it doesn't appear that you're doing so.

CollisionHandler collision = new CollisionHandler();

Upvotes: 0

Antony Scott
Antony Scott

Reputation: 21998

you need

CollisionHandler collision = new CollisionHandler();

You've just declared the variable but not set it to anything, hence the null reference exception.

Upvotes: 0

Phil Klein
Phil Klein

Reputation: 7514

You have not created an instance of your CollisionHandler object. Try something like this:

CollisionHandler collision = new CollisionHandler();
....
//CurrentX and CurrentY position to pass into addCollisionBox method and at the array number i
collision.addCollisionBox(currentX, currentY, i);

Upvotes: 1

Anthony Pegram
Anthony Pegram

Reputation: 126854

You have not created another instance, all you have done is create a variable of a given type.

CollisionHandler collision = new CollisionHandler();
//                 ^ variable           ^ instance of object

Upvotes: 2

George Johnston
George Johnston

Reputation: 32258

You didn't initalize your collision object. You should have something similar to the following. e.g.

CollisionHandler collision = new CollisionHandler();

...or how ever you are creating/grabbing an instance of your object prior to using it.

Upvotes: 6

Related Questions