In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set;
like:
private int myInt;
public int MyInt
{
get { return myInt; }
set { myInt = value }
}
My question is: how does this differ from:
public int MyInt;
and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!
I can't believe that with 11 answers, nobody has said this:
Not all private fields should be exposed as public properties. You should certainly use properties for anything that needs to be non-private, but you should keep as much of your class private as possible.
You have to use properties in the following cases:
In simpler words, answer to your question is the access modifiers i.e. public and private.
If you use:
then both MyInt property and myInt variable is available in the project to be modified. Means, if your class suppose A is inherited by class suppose B, then myInt and MyInt both are available for modification and no check can be applied. Suppose you want myInt value can be set in derive class if some particular condition pass.
This can be achieved only by making field private and property to be public. So that only property is available and conditions can be set based on that.
Well it does make a difference. Public data can be changed without the object instance knowing about it. Using getters and setters the object is always aware that a change has been made.
Remember that encapsulating the data is only the first step towards a better structured design, it's not an end-goal in itself.
The idea is you should not accidentally/unintentionally change the value of a class private field outside. When you use get and set, that means you are changing the class private field intentionally and knowingly.
Three reasons:
I'm sure there are more reasons that I'm just not thinking of.
In .Net 3.x you can use automatic properties like this:
instead of the old school way with declaring your private fields yourself like this:
This makes it as simple as creating a field, but without the breaking change issue (among other things).