You can't add to Players
because it is an IEnumerable
. Only specific kinds of IEnumerable
, such as lists and sets, can be added to. Here's one way your code can break: I (a user of your class) can set Player
to an IEnumerable
that you can't add things to:
var team = new Team("My Team", new Player[] { });
team.AddPlayer(new Player(...));
Now Player
is an array, which you certainly can't add to!
To allow adding things to Players
, you need to choose an type that allows adding. For example, an ICollection<Player>
, IList<Player>
, or List<Player>
.
public ICollection<Player> Players { get; set; }
public Team(string name, IEnumerable<Player> players)
Name = name;
Players = players.ToList();
}
// uncommenting the line in AddPlayer will now compile
You can make a private player
field of this type, and still expose a IEnumerable<Player>
if you want. But you need to remove the setter:
private List<Player> players;
public IEnumerable<Player> Players => players;
public Team(string name, IEnumerable<Player> players)
Name = name;
this.players = players.ToList();
}
public void addPlayer(Player pl){
players.Add(pl);
}