Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException and I Don't Know Why

I have two classes:

class Player
{
    public string Id { set; get; }
    public int yPos { set; get; }
    public List<Shot> shots;
    public Player(string _Id, int _yPos)
    {
        Id = _Id;
        yPos = _yPos;
    }

}
class Shot
{
    public int yPos { set; get; }
    public Shot(int _yPos)
    {
        yPos = _yPos;
    }
}

When I try to put new Shot in list of shots for the player I get NullReferenceException:

Player pl = new Player("Nick",50);
pl.shots.Add(new Shot(pl.yPos)); // this line throws exception

Probably something ultimately simple.

like image 538
Sergej Popov Avatar asked Apr 29 '26 13:04

Sergej Popov


2 Answers

In your Player constructor, just initialize shots = new List<Shot>();

like image 197
sazh Avatar answered May 02 '26 04:05

sazh


You need to new the shots in the Player constructor (or before you add to it).

shots = new List<Shot>();
like image 25
bryanmac Avatar answered May 02 '26 02:05

bryanmac