It may be hard to make code work in an uncertain future, but that's no excuse to be lazy. Coding a property over a field is convention and it's pragmatic. Call it defensive programming.
Other people will also complain that there's a speed issue, but the JIT'er is smart enough to make it just about as fast as exposing a public field. Fast enough that I'll never notice.
Some non-trivial things that come to mind
- A public field is totally public, you can not impose read-only or write-only semantics
- A property can have have different
get
versus set
accessibility (e.g. public get, internal set)
- You can not override a field, but you can have virtual properties.
- Your class has no control over the public field
- Your class can control the property. It can limit setting to allowable range of values, flag that the state was changed, and even lazy-load the value.
- Reflection semantics differ. A public field is not a property.
- No databinding, as others point out. (It's only a bug to you. - I can understand Why .net framework designers do not support patterns they are not in favour of.)
- You can not put a field on an interface, but you can put a property on an interface.
- Your property doesn't even need to store data. You can create a facade and dispatch to a contained object.
You only type an extra 13 characters for correctness. That hardly seems like speculative generality. There is a semantic difference, and if nothing else, a property has a different semantic meaning and is far more flexible than a public field.
public string Name { get; set; }
public string name;
I do recall one time when first using .net I coded a few classes as just fields, and then I needed to have them as properties for some reason, and it was a complete waste of time when I could have just done it right the first time.
So what reasons do you have for not following convention? Why do you feel the need to swim upstream? What has it saved you by not doing this?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…