Why prefer Properties to public variables? [duplicate]

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.

Leave a Comment