Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 714
ndsvw Avatar asked Dec 30 '25 05:12

ndsvw


2 Answers

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.

like image 66
Konrad Rudolph Avatar answered Jan 01 '26 17:01

Konrad Rudolph


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 getter 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.

like image 44
Athanasios Kataras Avatar answered Jan 01 '26 18:01

Athanasios Kataras