The general guidance for C# is to always use a property over a public field. This makes sense- by exposing a field, you're exposing a lot of implementation detail. With a property, you encapsulate that detail so it's hidden from consuming code, and implementation changes are decoupled from interface changes.
However, I'm wondering if there is sometimes a valid exception to this rule when dealing with the
readonly keyword. By applying this keyword to a public field, you make an extra guarantee: immutability. This is not just an implementation detail, immutability is something that a consumer might be interested in. Using a
readonly field makes it part of the public contract, and something that cannot be broken by future changes or inheritance without also having to modify the public interface. That's something that a property can't offer.
So is guaranteeing immutability a legitimate reason to choose a
readonly field over a property in some cases?
(For clarification, I'm certainly not saying you should always make this choice just because the field happens to be immutable at the moment, only when it makes sense as part of the class's design and it's intended usage to include immutability in its contract. I'm mostly interested in answers focussing on whether this may be justified, rather than specific cases where it's not, such as when you need the member to be on an
interface, or want to do lazy-loading.)