2003/02/06

Data-binding to public fields... yes or no?

To bind or not to bind to fields? This seems to be a source of constant debate, with folks in both camps. I get a mail roughly every six months in one form or another on this one. Today was that day.

I happen to be in the camp that disagrees that we should support binding to fields, because public fields are not a recommended practice. While they maybe convenient for quick and dirty code, they do not version. Using properties instead allows you to change the access logic, and data storage behind the covers, as well as add validation logic when a value is assigned. Furthermore, accessing properties feels pretty much the same, and do not have any performance overhead. Thankfully we have an FxCop rule to call out public fields as errors. Another reason, why I happen to in the disagree camp is overall consistency within the framework. For example, the property grid does not display fields.

Aside: One of the reasons why data-binding support is limited to properties happens to be the fact that all of data-binding is built around PropertyDescriptors and not on direct reflection. This allows someone to implement ICustomTypeDescriptor to provide a different OM for the purposes of data-binding than the true set of properties present on the CLR type. For example, DataRowView implements ICustomTypeDescriptor to surface its columns as pseudo-properties that are visible to ASP.NET's data-binding infrastructure (such as GridView/DataGrid columns and DataBinder.Eval). Without this, DataRowView would have two properties - DataView and Index (and the second is the only one remotely interesting for data-binding).

The web service proxies generated using wsdl in v1.x however (and unfortunately) generated only fields, and not properties. This is probably the most significant argument in favor of supporting binding to fields. In Whidbey however, this has been finally fixed, and properties are also generated.

I am curious what the general opinion is, and whether there is any chance for consensus on this subject!

I'll take advantage of this opportunity to voice a small gripe I have with C#. I'd really like the language to provide a shortcut for implementing properties where the compiler generates the get/set accessors and underlying private field in much the same way it does for events. For example, when all you want is a simple read/write property:

public property int Count;

and this can then be converted to a full-fledged property without changing the public OM of the type as needed.

Mercury簡易改裝

有同好有一樣的困擾 - 如何使用自己的data logging軟體,因此寫了這篇來分享我的簡易改裝。 Background 雲豆子 MERCURY roaster 烘豆機的設計是使用自行開發的軟體,來:1. 操控風門/火力; 2. data logging/自動烘焙。 ...