You're fundamentally misunderstanding the meaning of both of those definitions. Only exposing the getter says nothing about whether or not a value is read-only.
While in this trivial example:
public class GetOnly
{
public string MyProp { get; }
}
We can say that MyProp
will never change its value, we cannot always say that a getter-only property will not have its value changed. An example of this is a situation where we cannot see the implementation of GetOnly
, and only know about the public definition - For example, if you were working with a closed-source third party library.
A clearer example is this:
public interface ISomething
{
string MyProp { get; }
}
This interface does not say that MyProp
is read-only. It says that you cannot change the property. It says nothing about the behavior of the property. Even worse, it only says you cannot change the property when explicitly casting as ISomething
.
It's entirely possible to implement the interface like so (even though the interface only exposes the getter):
public class GetOnly : ISomething
{
public string MyProp { get; set; }
}
readonly
is a modifier which explicitly enforces the fact that the value will not ever change, except in the declaration or constructor (barring workarounds like reflection).
However, readonly
cannot work on properties, as properties are simply syntactic sugar for get/set methods. Further, interfaces only define methods, and as such you cannot define fields (and by extension, readonly fields).
So to answer your question: Yes, they are worlds apart, and are only similar on the surface.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…