2.5.8 readonly Fields

Video: Read-Only Fields (5:13)
readonly Fields

A Player turn limit should remain fixed while the count changes. A Team should also keep its roster-list reference while still adding players.

Initialize fixed configuration
Soccer example
public class Player
{
    private readonly int turnLimit = 3;
    private int numberOfTurns;

    public bool CanTakeTurn()
    {
        return this.numberOfTurns < this.turnLimit;
    }
}

The field initializer gives each Player its limit. Ordinary methods can read turnLimit but cannot assign a different value to it. The count is separate mutable state. Constructors later provide another permitted initialization point.

Protect the reference without freezing the list

This is a separate complete Team example. It uses the Player type above.

Soccer example
using System.Collections.Generic;

public class Team
{
    private readonly List<Player> players = new List<Player>();

    public void AddPlayer(Player player)
    {

        if (player != null)
        {
            this.players.Add(player);
        }
    }

    public int GetPlayerCount()
    {
        return this.players.Count;
    }
}
Apply the idea
Check your understanding