Sergej Popov
Sergej Popov

Reputation: 3021

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.

Upvotes: 3

Views: 2426

Answers (3)

Eric H
Eric H

Reputation: 1789

I like the below a bit better, only initialize shots if you need it and if you ever need to add logic to accessing Shots, you can without having to alter the use of Shots all over the place.

private List<Shot> _shots;

public List<Shot> Shots
{
    get 
    { 
        if (_shots == null) 
        {
            _shots = new List<Shot>();
        }
        return _shots;
    }
    set
    {
        _shots = value;
    }
}

Upvotes: 0

bryanmac
bryanmac

Reputation: 39296

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

shots = new List<Shot>();

Upvotes: 1

sazh
sazh

Reputation: 1832

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

Upvotes: 6

Related Questions