2.6.9 Initializing readonly Fields in a Constructor

Initializing readonly Fields in a Constructor

Different training areas can have different fixed capacities. Initialize each area capacity in its constructor, then prevent ordinary methods from replacing it.

Use a constructor initialization point
Soccer example
public class TrainingArea
{
    private readonly int capacity;

    public TrainingArea(int capacity)
    {
        this.capacity = capacity;
    }

    public int GetCapacity()
    {
        return this.capacity;
    }
}

Assume a positive capacity for these calls. The declaration makes capacity readonly; the constructor can assign it. A later ordinary method cannot assign another value to that field.

Keep independent configuration
Caller method
TrainingArea smallArea = new TrainingArea(6);
TrainingArea largeArea = new TrainingArea(12);
int smallCapacity = smallArea.GetCapacity();
int largeCapacity = largeArea.GetCapacity();

The results are 6 and 12. Readonly does not require all instances to store the same value. Each constructor invocation initializes its own instance.

Apply the same rule to owned storage

Inside a Team constructor, a private readonly List<Player> players field can be assigned new List<Player>(). Later Add calls can still change its contents. The readonly field protects the reference, not the list elements.

The field-initializer version demonstrates this same distinction.

Apply the idea
Check your understanding