hardfork
hardfork

Reputation: 3261

What's the benefit of a property with readonly getter?

I have seen readonly many times (often for members, but also in the context of readonly structs).

But what I've seen the first time is the combination readonly get for a property:

private double _x;
public double X
{
    readonly get => _x;
    set => _x = value;
}

But what does it mean? What exactly is the restriction of specifying a getter readonly?

Upvotes: 18

Views: 3585

Answers (2)

Athanasios Kataras
Athanasios Kataras

Reputation: 26362

This is not valid c# code. Check any compiler will get you:

The modifier readonly is not valid for this item

That is because the getter and setter are just syntactic sugar for functions.

For classes you are indeed right, that there is no point in a read only getter as there is no point in a read only function. Only variables have a point of being read only and properties only by not providing a setter.

https://dotnetfiddle.net/SPhTR8

For structs, it indicates that the greater does not change the state.

So that makes the following getter illegal:

// This will get you a compiler error
readonly get { _z = 7d; return _z; }

This is stated here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly

In an instance member declaration within a structure type, readonly indicates that an instance member doesn't modify the state of the structure.

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

The readonly get syntax is a new addition to C# 8. It signifies that the getter may not modify instance members.

Regular getters may modify the instance:

public double X
{
    get { _x = 1; return _x; }
}

That code is entirely valid; more usefully, a getter could for instance update a cached value. readonly get accessors cannot do that, and the compiler will enforce this invariant.

Upvotes: 25

Related Questions