Other being able to sanity check values in a setter is there a more underlying reason to prefer properties to public variables?
Use of properties makes your code more object oriented. By making member variables public, you are exposing your implementation. Save this answer.
You can use public variables as a shortcut to avoid the need to provide getters and setters, but there is no need to do so, and because there is a negative consequence (increased coupling to the internal design of the class) I would suggest that sacrificing design for brevity in this way is not often a good idea.
Bobb, Microsoft knows very well that no matter how much they trumpet design philosophy/shmilosophy, everybody would use public fields instead of properties once they realize that it's whooping 34% faster (even though it's a micro-optimization in 99.9% of the cases, people would do it anyway).
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.
We've had this subject before but I can't find anything now.
In brief: your needs might change: where there's no sanity check now, one might be required in the future. However, if you change your public fields to properties, this breaks binary compatiblity: every client who uses your code/library would have to re-compile.
This is bad because it potentially costs a lot of money.
Using properties from the beginning avoids this problem. This even counts for code that is not part of a library. Why? Because you never know: the code (even if highly domain-specific!) might prove useful so you want to refactor it to a library. This refactoring process is obviously made much easier if you are already using properties in place of public/protected fields.
Additionally, writing public properties is easy in C# 3.0 because you can just use the auto-implemented properties, saving you quite a bit of code:
public DataType MyProperty { get; set; }
Will implement the necessary backing field and getter/setter code for you.
I will add a personal note: .NET's behaviour in this regard is somewhat lazy. The compiler could just change public fields to properties on the fly, thus avoiding the problem. VB6 already did this for COM-exposed classes and I see absolutely no reason for VB.NET and C# not to do the same. Perhaps someone on the compiler teams (Jared?) could comment on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With