Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of using properties only with no corresponding fields in .NET?

Tags:

c#

.net

vb.net

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.

like image 375
Tony_Henrich Avatar asked Jul 03 '09 20:07

Tony_Henrich


People also ask

Why we use properties in C# instead of fields?

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.

What is the purpose of properties in net?

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.

What is the difference between properties and fields?

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.

What are the benefits of using properties?

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.


1 Answers

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.

like image 53
Marc Gravell Avatar answered Sep 28 '22 01:09

Marc Gravell