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

To bind or not to bind to fields?
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.
Posted on Monday, 8/23/2004 @ 8:21 PM | #ASP.NET


Comments

19 comments have been posted.

Vincent

Posted on 8/24/2004 @ 12:17 AM
I like the idea of the shortcut to quickly implement properties. It gets tedious to always retype the get set clauses. But it would of course mean that you should make an obvious link to the private field, if there is one, which could be the name of the property in lowercase. But this is a constraint on how you could name your fields/properties.

Joel Ross

Posted on 8/24/2004 @ 6:35 AM
If web service proxies generate properties instead of fields, then only binding to properties is fine with me! I use wsContractFirst (http://www.thinktecture.com/Resources/Software/WSContractFirst/default.html) to generate my stubs, mainly because it does just that.

Also, you can use a tool like AutoCode (http://www.devprojects.net/) in VS.NET 2003 to do just what you said - I type int MyProperty p and then press Ctrl-Enter, and I get:

private int _myProperty;
public int MyProperty{
get { return _myProperty; }
set { _myProperty = value; }
}

And of course, the code it produces is templatized, so you can change it.

Joel

Sergio Pereira

Posted on 8/24/2004 @ 6:43 AM
I happen to agree with most of what you say but I'm not sure if the framework should be the one trying to force programmers to use whatever is considered best practice. The list of best pratices changes all the time. Another argument is that not all the code written in .Net is for super-duper-enterprise-mission-critical-ultra-integrated scenarios. Having to write a ton of code just to adhere to best preactices when writing some command line utility seems like a depressing overhead. That's where suggestions like yours (for the property declaration) should be taken in consideration more seriously. Of course there are refactoring utilities in VS.NET 2K5 and some refactoring add-ins as of now but this would be a good language feature.

Kevin Dente

Posted on 8/24/2004 @ 11:05 AM
I too feel that if web service proxies had properties instead of fields, binding to fields would be a non-issue.

Also, I quite agree on the C# property idea.

David Taylor

Posted on 8/24/2004 @ 11:35 PM
Who do I need to speak with to get your C# property shortcut feature implemented? What is Anders email address?

I agree with all your suggestions; however over my last 4 years of using .NET I ended up writing my own Data Binding utility class allowing binding to fields to get around this restriction. I never really understood the "fundamental reason" ASP.NET never supported this and your blog entry is great. Having the web service proxies generate properties will solve 90% of peoples problems; but I still don't know if this should be enforced at the framework level; at least until you can write a property with a single line of code (as suggested in your example)

Bertrand Le Roy

Posted on 8/25/2004 @ 6:15 PM
At first, when I read your "property" keyword proposal, I thought yes, of course! And then, I started wondering what would be the real value of that? Wouldn't it just be pretending a field is a property? How different would it be from just promoting all public fields to properties? I'm pushing it a little but you see the idea. If we're considering that public int Count is bad practice, what exactly is better about public property int Count? Except to please some parts of the framework that only accept properties...

Leonardo Constantino

Posted on 8/25/2004 @ 7:08 PM
And for readonly properties:

public readonly property int Count;

Perfect! :)

Nikhil Kothari

Posted on 8/26/2004 @ 1:40 PM
Looks like there is some interest in this sort of syntax. I'll forward this on to the language folks.

I did want to respond to Bertrand's question. The idea behind this syntax is to a) acknowledge the simplicity of a field declaration and provide that simplicity to property declarations and more importantly b) allowing one to start with this simple field-like property declaration, and then later define explicit get/set accessors should the need arise for validation or change notifications (or something else), and to be able to do so without incuring a breaking change in the type's public object model. Thoughts?

Bertrand Le Roy

Posted on 8/26/2004 @ 6:13 PM
Yes, I guess as a starting point it makes sense. I guess I just don't write code this way, but as it seems to make sense for lots of people out there, I suppose I'm the one that's wrong ;)
Just to make it a little more useful, what about something like this (ugly syntax, just to give the idea):

[DefaultValue(0)]
public property int Count : ViewState["Count"];

which would stand for

[DefaultValue(0)]
public int Count {
get {
object o = ViewState["Count"];
return (o == null ? 0 : (int)o;
}
set {
ViewState["Count"] = value;
}
}

That would save us a lot of code!

Steve Celius

Posted on 8/27/2004 @ 5:21 AM
I'm all for autogenerating tedious and error prone code, like property declarations. I've written to mant get {} set {} statements in my life already! Found CodeRush from Developer Express, and I just can't code without it anymore. Not only property declarations, tempated code (try catch etc.), using statements, ifs, loops, blocks, ... you name it. If it's not there, you can add it yourself.

Brian Ritchie

Posted on 8/29/2004 @ 9:45 PM
Great timing! I just posted a customized version of the wsdl.exe tool that generates properties for web service client proxies. (http://weblogs.asp.net/britchie/archive/2004/08/30/222507.aspx) This problem was causing us serious heart-burn, but this tool works around it nicely.
Brian

Aaron

Posted on 8/29/2004 @ 11:35 PM
I'm for bertrand's suggestion. I never understood why there were properties *and* fields in C#.

Keith hill

Posted on 8/30/2004 @ 12:37 PM
Ditto on the easier property syntax. This would be just like what C# already does for you when you use the event keyword. The compiler crufts up the add/remove methods for you. Of course, you can provide your own impls for these if you want.

Ian Blackburn

Posted on 9/23/2004 @ 1:03 AM
I think there is a little bit of confusion in some of these replies regarding the property proposal - Bertrand appears to be suggesting that the code would stay in the form that was typed (public property int Count;), but I understood it to mean that it would expand to the full syntax. And of course, isn't that available using the Encapsulate Field refactoring in c# Whidbey? You type public int _count; select it and select Refactor > Encapsulate Field, enter the name of the property (Count would be the default) and it creates the property structure and makes the public field private. You could probably get it down to a single keystroke with a macro. CodeRush goes further I believe giving an autocomplete type thing using context aware shortcuts .

Eric

Posted on 10/3/2004 @ 8:27 PM
I apologize in advance if this is too far off topic, but I am desparately trying to understand how databinding actually works (just binding controls to properties in a user defined class, no datasets/databases, no web stuff) and have not found any good resources with nitty gritty details. If any of you could recommend anything I'd really appreciate it.

Thanks in advance...

Mike

Posted on 10/25/2004 @ 8:36 AM
What happened to your blog? Every few months, you'll post something very interesting...then you drop off the face of the Earth for awhile. :) Are you writing another book? Just curious...

Chris Gastin

Posted on 11/9/2004 @ 12:58 PM
I like the idea of providing a shortcut for generating the property from a private field. In the java world Eclipse has provided this functionality for creating getters and setters, and it is once of my favorite features. It make the grudge work so much faster. However I do not think that they should make this part of the C# language, but rather the a feature in VS.NET. I think that was the intent of your statement. If I am wrong please explain how they would make it part of the language. I am not quite following.

Chris Gastin

David Taylor

Posted on 12/17/2004 @ 5:06 PM
I dont know if you knew that C++/CLI supports a shortcut property syntax.

http://weblogs.asp.net/cnagel/archive/2004/12/17/323549.aspx

-------------------cut--------
C++/CLI has another syntax for properties where just the value is set and returned that doesn't need so much typing:

public:
property String^ Firstname;
-------------------------------

So...I really think we need this feature in C# as well!

AndrewSeven

Posted on 1/18/2005 @ 5:30 PM
"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."

So that is moot.

A fair number of my properties are really shallow and serve only for the property browser and binding an attribute to do the job of exposing the field might be interesting but might also be the path to macro code.

The captcha expires quickly...
The discussion on this post has been closed. Please use my contact form to provide comments.