The public fields debate again

Back in November last year I wrote about why you should make fields in a class private and not make them public. A recent post in Code Project shows that some people still make fields public. I did concede on one argument though – If you have a struct with nothing but public fields then there was no need to make them private and create public properties to back them. But, I added….

As soon as you put any form of functionality in there (or even if you think that at some point in the future there will be some form of functionality in there) then make them private and create properties.

While accessing public fields and properties may look the same to a C# developer, a property is just syntactic sugar over the get_ and set_ methods. So if you make the transition to properties later on (for to add additional functionality – e.g. implementing a lazy look up on a getter, or setting a dirty flag on a setter) any assemblies that relied on public fields will fail because, to them, the public interface of the class is now different.

Therefore if you get in to the habit of creating properties backing your private fields always you’ll never have to worry about how you are going to add in additional functionality later on when you realise the public interface changes.

NOTE: This was rescued from the Google Cache. The original date was Saturday 17th June 2006.

Tags:


Original Comments:

There is nothing wrong with using public fields in an non-public accessable class.

6/17/2006 5:52 PM | leppie

I dont think its wrong to have public fields in a lib as long as you dont plan on beeing binary compatible, since binary compatabillity breaks the day you change one of those fields to a property..

6/18/2006 6:36 AM | Roger Johansson

leppie – I’ll accept that is also another place where it might be okay to use public fields.

6/23/2006 9:53 PM | Colin Angus Mackay

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s