public variables - need of properties C# [duplicate]
Possible Duplicate:
C#: Public Fields versus Automatic Prope开发者_如何学编程rties
I read properties in C# are declared or used to provide access of private members to others. In that case, when we are declaring public members, do we still have to declare properties for them.
In the following example, they have declared properties for public members. I don't know why ?
class Customer
{
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
}
thanks!
This article gives you a good overview to properties and its overuse http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html
Using properties instead of public fields allows non-breaking changes in how these properties are implemented in the next release - with public fields any change is breaking.
For example you could change the implementation of TotalPurchases
to perform a calculation instead of returning the value of a backing field directly. From the point of view of the consumer of the class this change is non-breaking and does not affect how your application works.
public double TotalPurchases
{
get
{
return CalculatePurchases();
}
}
So first of all, properties in C# are declared for many reasons, and it's not about being private at all.
You can, for example, make the getter public and the setter private:
public double TotalPurchases
{
get;
private set;
}
Also, for some frameworks backed up by reflection, they look for properties and not fields. In this case, properties are a must, even if it looks useless when nothing is done in the getter/setter.
精彩评论