Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we use public fields for data binding in C#?

I am aware of the advantages of using properties over fields, like being able to provide additional logic when required in the future.

But I really wonder why it's not possible to use public fields for data binding or even for JSON serializers like JavaScriptSerializer class.

Is there any good reason to ignore public fields in these cases? Or is it just some kind of convention? Or just to force users to use properties?

like image 792
sapito Avatar asked Dec 20 '14 16:12

sapito


2 Answers

The short version is that always using properties instead of public (or, really, even protected) fields has been a fundamental design choice in .NET since the very beginning.

The slightly longer version is that adding support for public fields would add complexity to the data binding framework (whichever one you're referring to). Fields also lack any kind of support for change notification, which is a fairly important aspect of data binding (at least in a stateful environment like Winforms development). Even at the level of retrieving and setting values, fields and properties are different; while the syntax in VB.NET or C# for retrieving or setting the value of a property is (by design) the same as that of a field, the mechanism used to do this in a programmatic scenario like data binding is different for properties vs. fields.

In the end, this all just means that it would take more work to add support for public fields to any data binding scenario, so since it's an anti-pattern anyhow this work isn't done.

like image 84
Adam Robinson Avatar answered Oct 25 '22 11:10

Adam Robinson


There is no technical reason behind this restriction: it is certainly possible to add public fields to the list of properties, and allow binding to them. In fact, there are APIs in .NET that would pick a property or a public field automatically, based on a name alone. For example, LINQ's Expression has PropertyOrField method that would pick one or the other, based on the type returned by the expression in its first parameter.

However, leaving fields public exposes you to such an array of potential problems, that the designers of systems dependent on reflection often try to discourage use of public fields by withholding support for them from their system design.

In addition, in systems that rely on events for binding, using a field would not be possible for technical reasons, because one cannot fire an event on setting a public field.

like image 24
Sergey Kalinichenko Avatar answered Oct 25 '22 11:10

Sergey Kalinichenko