Consider using public fields instead of properties

So another crazy suggestion for making C# a little less verbose. This time I am suggesting that you consider using public fields instead of properties.

So what are properties for?

From http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx > Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

So it allows us to encapsulate logic within the property get and set. This way we can change the implementation details without effecting consumers of the member.

We all hopped on the bandwagon

I must admit for a long time I have blindly followed this advice. Any member I want to expose I made it a property instead of a public field. Even better when automatic properties came out, now I could follow the advice with less code. So now almost every codebase contains code like this

public xxx Property{get;set;}

So are properties always required?

The reality is that there are cases that properties are required

  • You actually have logic in the get and set. If not what are you trying to encapsulate?
  • You assembly is being referenced by a third party
  • You are integrating with a tool or library that only supports properties, i.e. it does not support fields.

However for all other cases you should be using public fields. If you ever change your mind you can change your field to, rebuild and continue on. So the thought process for choosing between properties and public fields is as follows:

When to use public fields

So I propose

That the {get;set;} of this
public xxx MyMember {get;set;} Is noise and should be removed
public xxx MyMember;

Posted by: Simon Cropp
Last revised: 20 Dec, 2011 10:56 AM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.