C# readonly vs Get

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.


At first glance the property and the field are functionally equivalent and for the normal use cases of storing data and passing it around there is not much difference in using them.

But you already seem to have found an important issue: Only properties can be part of an interface.

is there a way to make an interface that works with both?

No.

In addition, many APIs that rely on reflection (EF, Serialization) specifically look for properties.


In the following part:

public class GetOnly
{
    public string MyProp {get; }
}

MyProp is a property. However, in this part:

public class ReadOnly
{
    public readonly string MyProp;
}

MyProp is a field. These are two different things.

is there a way to make an interface that works with both?

No. Only properties can be put into interfaces. Fields cannot.

Tags:

C#

Properties