Honestly, what's the difference between public variable and public property accessor? [duplicate]
Possible Duplicates:
What is the difference between a field and a property in C# Should I use public properties and private fields or public fields for data?
What is the difference between:
public string varA;
and
public string varA { get; set; }
The public property accessor gives you more flexibility in the future.
If you want to add validation to setting the value, you simply write a non-default setter. None of your other code would have to be modified.
There could also be reasons you'd want to replace the default getter with code. That can be a real pain with a public variable.
In addition to the other answers, you can also use a property to make the value read-only or even set-only:
public int Item { get; private set; } // read-only outside the class. Can only be set privately.
I have also run into situations where I later decide I want to proxy an object, or add AOP, which basically requires properties.
Public property accesses fields and internal class code through exposed getter and setter methods. A public field acesses the field directly.
Using propertys offers the potential to provide a layer of abstraction and design (ability to make set accessor protected, private).
When a property is specified and no body present an underlying private field is created by the compiler that is used to store the value against. Essentially:
private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}
In general I tend to use properties for public exposed variables and fields for private. I might consider using a field if that field was accessed many times and speed was a crucial design requirement.
精彩评论