开发者

public variables - need of properties C# [duplicate]

开发者 https://www.devze.com 2023-04-10 16:01 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: C#: Public Fields versus Automatic Prope开发者_如何学编程rties
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消