I have classes which have automatic properties only like public customerName {get; set;}. They are public because they are accessed outside the class. They can also be accessed inside the class. They offer good encapsulation and better debugging. I can put a breakpoint on one if I need to know who is accessing it and when.
My question is what are the disadvantages of using properties only with no corresponding fields? I can make the setter or getter private, internal.. etc which means I also have flexibility of scoping it when needed.
In almost all cases, fields should be private. Not just non-public, but private. With automatic properties in C# 3, there's basically no cost in readability or the amount of code involved to use a property instead of a field.
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.
Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.
Answer: The advantages of using properties are: Before allowing a change in data, the properties can validate the data. Properties can evidently make visible of data on a class from where that data is actually retrieved such as a database.
Serialization with BinaryFormatter
- you have big problems if you need to change your property to a "regular" property later, for example to add some validation / eventing /etc - sinc BinaryFormatter
uses the field names. And you can't duplicate this, since the field name the compiler generates cannot be written as legal C#.
Which is a good reason to look at a contract-based serializer instead. See this blog entry for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With