I am going through a tutorial on XNA, and it uses this code:
private int score = 0;
public int Score
{
get { return score; }
set { score = value; }
}
What is the point of using a property? Why not just use public int Score = 0;
?
I am going through a tutorial on XNA, and it uses this code:
private int score = 0;
public int Score
{
get { return score; }
set { score = value; }
}
What is the point of using a property? Why not just use public int Score = 0;
?
I would just use an auto-property here:
public int Score { get; protected set; }
as it's "the same thing with less typing" (but actually perhaps better because it limits who can set the score ;-)
Some reasons for properties (over public Member Variables):
Properties allow setting the visibility for the getter and setter individually, as shown above.
Properties can be specified in Interfaces. (You are programming against interfaces ... right? ;-)
Switching between Properties and Member Variables breaks the ABI (Application Binary Interface: e.g. needs a recompile against). However, an existing Property's implementation can be re-defined without breaking the ABI.
Breakpoints can be set in Properties. Occasionally very handy.
"Encapsulation"
By making fields public you expose an implementation detail. It's possible that "Scoring" in future won't be a simple value to be returned, but the result of a computation, so by hiding it behind an abstract "GetScore" property function you're free to alter the details of your implementation without breaking consumers.
Note that you can use automatically-generated fields with properties in C# 3.0:
public int Score { get; set; } // this will create a hidden field, however all access (even from within the class) must be done by the accessor and mutator methods.
The biggest reason is for ease of refactoring to include logic. (Changing from a field to a property requires a recompile in assemblies referencing yours, since the get and set accessors are actually methods.) As pst's comment showed, you can also assign different access modifiers to the get and set (e.g. protected set
). With auto-properties, there's usually little to no reason (in readability or anything else) to go with a field instead of a property.