2008-11-14

Why We Must Use Classes Instead of Structs for Read/Write DataBinding in C#

Structs are Value Types.
Classes are Reference Types.

When we DataBind in C#, if we're using Value Types... we get copies of those objects instead of pointers to them, for that's how they are passed to the bound control. Therefore, you can't edit the bound control and expect the original objects to be modified. The bound control is only editing the copies and thus we encounter side effects when DataBinding a list or array of value types (like structs.)

I ran into this on a project I was working on where I needed to show a DataGridView for editing attributes. My attribute representation was a struct with a name property and value property... and when I bound a BindingList to the DataGridView, the list would appear... but when I'd edit the values would return to the old values... and when I'd add rows, the values would disappear.

The explanation above explains why. It didn't dawn on me until I started searching for "BindingList structs" and found Bill Wagner's "Of DataBinding and Value Types" (archive.org since the site is no longer available). The title tipped me off because I wasn't thinking about the fact that structs are value types.

Bill's article explains in more eloquent detail than I care to go into here, as I don't feel the need to re-write a well written essay on the topic. I only hope to provide a quick answer for those searching for it, that don't find Bill's article first (and leave myself a quick reference when I forget the next time I try to use a struct...)

He also mentions in his article when it is appropriate to use structs. Thanks for a well-done article, Bill.

So, reminder: use classes instead of structs when you need to do read/write binding. If you're merely databinding for a viewable list... use structs as you like.

No comments: