2.7.6 Read-Only Properties

Read-Only Properties

The coach can read the number of turns while Player retains responsibility for recording them. A getter-only property offers information without an assignment path.

Expose the current result
Soccer example
public class Player
{
    private int numberOfTurns;

    public int NumberOfTurns
    {
        get
        {
            return this.numberOfTurns;
        }
    }

    public bool RecordTurn()
    {

        if (this.numberOfTurns < 3)
        {
            this.numberOfTurns = this.numberOfTurns + 1;
            return true;
        }

        return false;
    }
}

The property has get but no set accessor. The training action still changes the private count. This is the same three-turn application rule used in the method-based design.

Distinguish read-only access from unchanged state
Caller method
Player jordan = new Player();
int before = jordan.NumberOfTurns;
bool accepted = jordan.RecordTurn();
int after = jordan.NumberOfTurns;

before is 0, accepted is true, and after is 1. The earlier local value stays 0. An outside assignment to jordan.NumberOfTurns would fail to compile because the property has no setter.

Consider what a returned reference permits

Return the roster count or provide a registration operation when callers do not need the list itself. Keep private arrays and collections inside their owner.

Apply the idea
Check your understanding