Question

I have a class Club which has a list _list as an argument, while 'Player' is another class ... I have this method for adding the club members, thas is implemented this way:

public void AddPlayer(Player p)
{
    if(_list.Contains( p)) 
        throw new Exception("The Player " + p.Name + " " + p.Surname + " is already a         member of this club!");
    _list.Add(p);
}

Now, when I do this in my main program:

Player p = new Player("Christiano", "Ronaldo", 1993);
Club club = new Club("ManUtd", coach);
club.AddPlayer(p);

It throws an exception that says that object reference is not set as an instance of an object.

Was it helpful?

Solution

(Constructor code grabbed from OP comment.)

In your constructor, it appears that you just initializing a local variable within that method, not the field _list.

public Club(string clubName, Coach mycoach) 
{ 
     List<Player> _list = new List<Player>(); 
     ClubName = clubName; 
     Mycoach = mycoach; 
}

Try changing

 List<Player> _list = new List<Player>(); 

to:

 _list = new List<Player>(); 

OTHER TIPS

Sounds like your _list instance variable is null. Try initializing it:

public class Club {
    private List<Player> _players = new List<Player>();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top