简体   繁体   中英

How can I pass an object instance in a method call in C#?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM