Bill Blogs in C#

Bill Wagner discusses C#, LINQ, and other items of interest

Data Binding with immutable Types?
It does work, if you are not changing the data. In fact, that's the preferred way if the user is not allowed to change the data.

I received the following question (which does related to Effective C#). I thought the discussion was of general interest, so I posted it here instead of in the blog relating to the book:

I have a question about some recommendations that seem to conflict. Item 7 (Prefer Immutable Atomic Value Type) and Item 38 (Utilize and Suuport Data Binding) seem to contradict each other. It was my understanding that the data binding classes only worked on public properties to synchronize data. If you only provide "get" properties and not "set" properties, how would this work?

It is correct that Data Binding works by reflecting on public properties to synchronize data between controls and data objects.

The first answer is quite simple: If you only provide get accessors, you can transfer the data value from the data object to the control (either a web control or a windows control). You’ll see in Item 38 that I have some examples of this technique. Those are the examples that use a property on a data object to set the foreground or background color of a control. Being read-only properties, there is no way to store the data back into the data object. When that’s what you want, it works just fine.

The second answer is a bit more complicated. You’ll note that I stated in Item 7 that not every type can be an immutable type. Some of your low-level data storage objects should be immutable, and should be value types. But, if everything is immutable, your users cannot change anything in your program. Once again, look at the examples in Item 38. Some support edits: those are not immutable. Some (like the color example) are immutable.

Finally, let’s look at these two recommendations in concert. You could have a mutable type (an employee record for example) contain an immutable type (like an address structure). You could support data binding and transactions using these two types. You would expose the get and set accessors on the employee record. The set methods could create copy of an internal address structure. You can see this idiom in Item 41. (It is in a counter example, but there are times when it is the correct idiom.)



Published Tue, Mar 1 2005 5:21 AM by wwagner
Filed under: ,