Why can't we use public fields to bind data in C #?

I know about the advantages of using properties over fields, for example, about the possibility of providing additional logic when necessary in the future.

But I really wonder why it is not possible to use public fields for data binding, or even for JSON serializers such as JavaScriptSerializer.

Are there good reasons to ignore public fields in these cases? Or is it just some kind of convention? Or just get users to use properties?

+8
c # serialization data-binding
source share
3 answers

The short option is that always using properties instead of public (or, indeed, even protected ) fields has become a fundamental design choice in .NET from the very beginning.

A slightly longer version is that adding support for public fields would add complexity to the data binding structure (depending on what you're talking about). The field also lacks any support for notification of changes, which is a rather important aspect of data binding (at least in a stateful environment such as Winforms development). Even at the level of extracting and setting values, the fields and properties are different; while the syntax in VB.NET or C # to retrieve or set the value of a property (by design) is similar to the field syntax, the mechanism used for this in a programming script such as data binding is different for properties vs. fields.

In the end, all of this simply means that adding support for open fields to any data binding scenario will require more work, therefore, since this is an anti-pattern, this work is not performed.

+6
source share

There is no technical reason for this restriction: of course, you can add public fields to the list of properties and allow binding to them. In fact, in .NET there are APIs that automatically select a property or public field based only on a name. For example, LINQ Expression has a PropertyOrField method that will select one or the other based on the type returned by the expression in its first parameter.

However, leaving the fields open, you are faced with so many potential problems that reflection-dependent system designers often try to impede the use of public fields by denying them support for their system design.

In addition, in systems that rely on events for binding, the use of the field would be impossible for technical reasons, since it is impossible to create an event when setting up a public field.

+3
source share

Since you cannot declare fields in interfaces, you should not use Public Fields. All fields should only be private.

If your code depends on abstractions, you need to use interfaces, and open fields are not available here.

0
source share

All Articles