Properties vs Public member variables

user1230593 picture user1230593 · Aug 9, 2012 · Viewed 21.1k times · Source

Possible Duplicate:
What is the difference between a field and a property in C#

I'm a beginning programmer and I've read all about class properties. Books state that properties allow you to indirectly access member variables. Ok, so what makes it any different than just making the field public and accessing it directly?

Here's a quote from Learning C# 3.0 by Jesse Liberty:

For example, you might want external classes to be able to read a value, but not change it; or you might want to write some code so that the internal field can accept only values in a certain range. If you grant external classes free access to your member fields, you can’t control any of that.

I don't understand what he is saying here. Can someone further explain this or give an example of why I would want to use a property over making the field public. As I understand it now they would both accomplish the same exact thing...so I'm obviously missing something here.

Answer

Dai picture Dai · Aug 9, 2012

The other answers provided so far provide details of the advantages of accessor/mutator logic, but all seem to miss out on the ideological point about object encapsulation.

You see, class member fields are an implementation detail. If you have a class that represents a collection, for example, then you could implement it as a linked list (and expose the root-node via a public field) or you could implement it as a resizable array and expose the index0 member.

The problem with revealing implementation details is that you lose any kind of defined interface between your class and its consumers. By ensuring all operations are done via defined methods (controlled by the class itself) you make it easier to work with and provide for a long-term viewpoint. For example, you are far more easily able to convert your collection implementation from one type (the linked-list) to another (the array) without breaking any contracts with your class' consumers.

Don't worry about any performance impact of trivial accessor/mutator methods: the JIT compiler will inline the property methods. If you'll run some benchmarks you'll see the performance of properties vs fields is identical.