This post originated from an RSS feed registered with .NET Buzz
by Eric Gunnerson.
Original Post: Public fields vs properties
Feed Title: Eric Gunnerson's C# Compendium
Feed URL: /msdnerror.htm?aspxerrorpath=/ericgu/Rss.aspx
Feed Description: Eric comments on C#, programming and dotnet in general, and the aerodynamic characteristics of the red-nosed flying squirrel of the Lesser Antilles
If you search on MSDN, you won't find any general C# coding guidelines. When
people have asked how they should write their code, they often get pointed to the class
library design guidelines. There is lots of good advice there, but not all
of it applies universally.
One of the guidelines says:
Do not use instance fields that are public or protected
it goes on to say that this is important because properties don't version well.
Some people have taken this as an absolute rule, so I've been seeing lots of code
that uses properties on every class. If you don't need the versioning advantages
of properties, you don't need to spend the time writing lots of trivial properties
(those where the getter and setter don't do anything special).
In fact, I'll say that a bit stronger. You probably shouldn't use properties unless
you need them, as it takes more work and makes your classes harder to read
and maintain.
So, when should you use properties that you don't need? My suggestion is to only
use them at versioning boundaries. If a class and the classes that use it are always
compiled together, than properties don't buy you any advantage. If they are compiled
separately, then using properties instead of fields looks like a better idea.
Or, to put it another way, writing trivial properties makes sense at the locations
where your component interfaces with other components.