C# 8.0 introduced readonly
members in a struct (as explained here). So for instance you can have this method:
public readonly override string ToString() => $"({X}, {Y}) is {Distance} from the origin";
Also, if your readonly
method modifies a state of the struct it won't compile - which I find quite useful and elegant solution. So for instance, in the example below if X
and Y
are properties of a struct the following method won't compile:
public readonly void Translate(int xOffset, int yOffset)
{
X += xOffset;
Y += yOffset;
}
Again, very useful and elegant way to express the intention of the code.
Why then it is only possible with structs and not with classes. If I try to add readonly
to a method in a class I get a compiler error: The modifier 'readonly' is not valid for this item.
Are there any limitations of a reference type where having a readonly method doesn't make sense?