Properties and indexers

Properties and indexers present field-like and indexed syntax while routing reads and writes through accessor bodies.

Properties

A property declares a type and a name followed by a get accessor, a set accessor, or both. The setter receives the assigned value through the implicit name value.

struct Player
{
    private int health;

    public Player(int initialHealth)
    {
        health = initialHealth;
    }

    public int Health
    {
        get { return health; }
        set { health = value; }
    }
}

Player player = Player(100);
player.Health = 80;
int health = player.Health;

A property is an accessor abstraction, not an implicit field. It occupies no additional space in the struct layout; storage is explicit in fields such as health.

Getter-only properties

Omit set when callers should be able to read a computed value without assigning to it.

public readonly int Health
{
    get { return health; }
}

The readonly modifier also permits the getter to be called through a readonly struct receiver.

Indexers

An indexer uses this[parameters] and the same getter/setter model. Reading invokes get; assignment invokes set with the assigned value available as value.

struct Buffer
{
    private int* data;

    public int this[int index]
    {
        get { return data[index]; }
        set { data[index] = value; }
    }
}

buffer[5] = 10;
int item = buffer[5];

Multiple parameters and overloads

An indexer may accept multiple parameters. A struct may declare several indexers when their parameter type lists differ; normal overload resolution selects the matching declaration.

public float this[int x, int y]
{
    get { return GetValue(x, y); }
    set { SetValue(x, y, value); }
}

float sample = matrix[4, 7];
matrix[4, 7] = 1.0f;

Compound assignments

Compound assignments preserve accessor behavior. An expression such as player.Health += 5 performs one property read and one property write; index arguments are evaluated once for an indexed compound assignment.

player.Health += 5;
buffer[index] -= 1;