For the most part, in practice, the public field will be good. After all, if you later need to make it read-only from the outside or add behavior to its setter, you can simply change it to a property. So you can make this a public field today and change it later if you need to. Right?
The fact is, there are some cases where you cannot safely change it later:
- If you compile Foo.dll with a public field, and someone creates Bar.dll that refers to Foo.dll, you will not be able to add a new version of Foo.dll later with this field changed to a property. You would need this other person to rebuild Bar.dll against your new Foo.dll. For some stores, this is not a problem; for others, this can be a huge problem.
- If you write some kind of reflection code, the reflection from the fields is very different from the reflection of the properties. Therefore, if you later change your field to a property, your Reflection code will break.
How important are both of these scenarios? Probably not very. But it's easier to write proactively
public string PropertyName { get; set; }
than clearing up the mess if you need to change it later.
And there is no cost of execution. In any case, the JIT compiler will inline the getter and setter. So it costs nothing and brings some benefit; at this point why not use the property?
source share