2.7.11 Calculated Properties

Video: Calculated Properties (8:55)
Calculated Properties

Team can report roster size and whether it has room without maintaining extra fields that must be updated after every registration.

Derive information when it is read

Use the Player from the getter-only turn-count lesson.

Soccer example
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.

Compare results before and after actions
Fresh Team with distinct non-null Players
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.

Apply the idea
Check your understanding