Type safety

I had a look at the following code:

cmbSomeComboBox.DataSource = MySource;
cmbSomeComboBox.DisplayMember = "Description";
cmbSomeComboBox.ValueMember = "Code";

This assumes that MySource contains an list of  objects MyObject with property "Description" and "Code".

If for some reason you change the MyObject class (get rid of either Code or description) your code will still compile fine but it will throw a argumentException on runtime. It is nicer to have a compile time error..
The only solution I could come up with is this:

Debug.Assert(new MyObject().Description.GetType() != null, "Description property gone?");

This will give a compile time error...for now I didn't find a nicer way to come up with compile time binding without a lot of hassle.

Published 02-25-2006 2:24 PM by Rene Schrieken

Comments

# re: Type safety

Wait for C# 3.0 and LINQ ;) It will give you a way to project out the Description and Code properties (in a strongly typed manner) into a new IEnumerable<anonymous type>:

cmbSomeComboBox.DataSource = from item in MySource select item.Description, item.Code;
cmbSomeComboBox.DisplayMember = "Description";
cmbSomeComboBox.ValueMember = "Code";

This code will no longer compile when MySource has no Description and Code properties.

Monday, February 27, 2006 1:06 AM by Erwyn van der Meer

Leave a Comment

(required) 
(required) 
(optional)
(required)