1

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.

ssedano
  • 8,322
  • 9
  • 60
  • 98
Nicky Name
  • 101
  • 2
  • 9
  • How do you initialize the _list variable? – Steve Nov 01 '13 at 23:05
  • Please show us the code where you're initializing `_list`. I suspect it's still `null`. – musical_coder Nov 01 '13 at 23:06
  • 1
    In general, the best way to troubleshoot stuff like this is to set a breakpoint in the method, and then walk through it until you hit the exception. That'll usually tell you where to look. – Ken Smith Nov 01 '13 at 23:07
  • this is my constructor for class Club : public Club(string clubName, Coach mycoach) { List _list = new List(); ClubName = clubName; Mycoach = mycoach; } – Nicky Name Nov 01 '13 at 23:08

2 Answers2

2

(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>(); 
Tormod
  • 4,551
  • 2
  • 28
  • 50
  • you were right! That is why all other constructors were working just fine :D I just copy pasted the whole declaration of _list! :D thanks so much, now it works :) – Nicky Name Nov 01 '13 at 23:17
1

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

public class Club {
    private List<Player> _players = new List<Player>();
}
ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152
  • this is my constructor for class Club : public Club(string clubName, Coach mycoach) { List _list = new List(); ClubName = clubName; Mycoach = mycoach; } – Nicky Name Nov 01 '13 at 23:07
  • @NickyName: Tormod has it right. Consider always using "this." to reference instance fields and properties. That way, you'll be guaranteed not to get this error. – ChaseMedallion Nov 02 '13 at 12:53