// add a player to the team, if not already in the team public void AddPlayer(SoccerPlayer player) { if (players == null) // empty { players.Add(player); } else { if (players.Contains(player)) // already in the team, Contains uses Equals for SoccerPlayer to test presence { throw new ArgumentException("Exception: player " + player.Name + " is already in the team"); } else { // add the plater if (player.Gender == TeamGender) { if (player.Age <= AgeLimit) { players.Add(player); } else { throw new ArgumentException("Exception: player " + player.Name + " is too old for team " + TeamName); } } else { throw new ArgumentException("Exception: player " + player.Name + " is " + player.Gender + " while team is " + TeamGender); } } } }
// indexer property, return a player with specified name public SoccerPlayer this[String playerName] { get { SoccerPlayer player = null; Boolean found = false; for (int i = 0; i < players.Count; i++) { if (String.Compare(players[i].Name, playerName, StringComparison.OrdinalIgnoreCase) == 0) // ignore case in comparison { found = true; player = players[i]; } } if (found) { return(player); } else { throw new ArgumentException("Exception: Player " + playerName + " is not in the soccer team " + TeamName); } } }
// custom equality comparison for .Equals, used by Contains() on List<> public override bool Equals(Object obj) { SoccerPlayer player = obj as SoccerPlayer; if (player == null) { return(false); } // must match all 4 attributes to be equal if ((player.Name == this.Name) && (player.Age == this.Age) && (player.Gender == this.Gender) && (player.Position == this.Position)) { return(true); } else { return(false); } }