2.7.8 Property Access Modifiers

Video: Alternate Visibility of Property Set Methods (8:01)
Property Access Modifiers

A TrainingArea should report its temperature publicly while accepting changes only through its own actions. A public property can have a more restrictive setter.

Give reading and assignment different access
Soccer example
public class TrainingArea
{
    private double temperature;

    public TrainingArea()
    {
        this.Temperature = 20.0;
    }

    public double Temperature
    {
        get
        {
            return this.temperature;
        }

        private set
        {
            this.temperature = value;
        }
    }

    public void IncreaseTemperature()
    {
        this.Temperature = this.Temperature + 0.5;
    }
}

The property is public, so outside code can read it. The private setter can be used by TrainingArea code, including its constructor and action. This visibility example does not yet enforce temperature bounds.

Test the allowed public surface
Valid caller method
TrainingArea area = new TrainingArea();
area.IncreaseTemperature();
double shownTemperature = area.Temperature;

The result is 20.5. An outside area.Temperature = 22.0 assignment is intentionally forbidden. Calling IncreaseTemperature is permitted because that action is public.

Apply the idea
Check your understanding