Different training areas can have different fixed capacities. Initialize each area capacity in its constructor, then prevent ordinary methods from replacing it.
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.
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.
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.