Team can report roster size and whether it has room without maintaining extra fields that must be updated after every registration.
Use the Player from the getter-only turn-count lesson.
using System.Collections.Generic;
public class Team
{
private readonly List<Player> players = new List<Player>();
public int PlayerCount
{
get
{
return this.players.Count;
}
}
public bool HasRoom
{
get
{
return this.players.Count < 2;
}
}
public bool AddPlayer(Player player)
{
if (player != null && this.HasRoom)
{
this.players.Add(player);
return true;
}
return false;
}
}Two is this small training-group capacity, not a soccer-team regulation. HasRoom computes its Boolean answer from the current list. PlayerCount reads Count; neither property needs a second field.
| Moment | PlayerCount | HasRoom |
|---|---|---|
| Before additions | 0 | true |
| After first successful addition | 1 | true |
| After second successful addition | 2 | false |
| After rejected third addition | 2 | false |
An array-based area can similarly count non-null occupants in its getter with a loop. Keep the array private and return the calculated count, not the storage.