문제

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.

도움이 되었습니까?

해결책

(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>(); 

다른 팁

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

public class Club {
    private List<Player> _players = new List<Player>();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top