Versioning:
I think this does not really matter if you are only interested in source compatibility.
Using a property is better for binary compatibility, since you can replace it with a property that has a setter without breaking the compiled code depending on your library.
Convention:
You follow the convention. In such cases, when the differences between the two possibilities are relatively insignificant in accordance with the agreement, it is better. One case where he may return to bite you is a reflection-based code. It can only accept properties, not fields, such as a property editor / viewer.
Serialization
The transition from field to ownership is likely to lead to the breakdown of many serializers. And AFAIK XmlSerializer serializes public properties, not public fields.
Using Autoproperty
Another common variation is the use of an autoprocessor using a private setter. Although this is short, the property does not provide read consistency. Therefore, I prefer others.
Readonly field is self-documenting
There is one advantage of the field:
This makes it clear at a glance at the public interface that it is virtually immutable (ban on reflection). If in the case of a property you can only see that you cannot change it, you will have to refer to the documentation or implementation.
But to be honest, I use the first one quite often in the application code, since I'm lazy. In libraries, I tend to be more careful and stick to the agreement.
C # 6.0 adds readonly automatic properties
public object MyProperty { get; }
Therefore, when you do not need to support older compilers, you can really have a readonly property with code that is as concise as the readonly field.
CodesInChaos Oct 12 2018-10-10 18:39
source share