Combining Anonymous Types with Dynamic

Sunday, September 25, 2011 / Posted by Luke Puplett /

This short blog post shows the outcome of a quick experiment. I am researching a way to back a WPF View with a ViewModel whose properties are not known until runtime.


It’s been a long time since I last blogged. I built a house, I’ve had a baby, well, Cassie did the hard work, and also worked on a very large Silverlight project for a large investment bank (a foreign exchange trading platform) and then moved again to a start-up in the West End of London.

The former job was all hush-hush and even though our small team had the pleasure of a couple of exclusive hours with Silverlight evangelist Mike Taulty, we weren’t able to tell him what we were working on. So blogging was out of the question, which is a real shame for me and the community as a whole, in my opinion (although understandable).

The Interesting Bit
Anyway, while playing this afternoon, I discovered that anonymous types can escape the confines of the scope they’re declared in by returning them as dynamic!
Check this out:
1 static void Main(string[] args) 2 { 3 var rows = ReadDynamicRows(); 4 5 foreach (var row in rows) 6 Console.WriteLine(row.Id); 7 8 object o = rows[0]; 9 var properties = o.GetType().GetProperties(); 10 } 11 12 private static List<dynamic> ReadDynamicRows() 13 { 14 dynamic row; 15 List<dynamic> rows = new List<dynamic>(); 16 using (var reader = 17 DataHelper.ExecuteSqlStatementReader( 18 DataHelper.BuildConnectionString(), 19 "SELECT TOP 1000 * FROM SomeTable")) 20 { 21 while (reader.Read()) 22 { 23 row = new 24 { 25 Id = reader.GetString(0), 26 }; 27 28 rows.Add(row); 29 } 30 } 31 32 return rows; 33 }


What’s really interesting to me is that the properties can be reflected upon. In my experiments with the dynamic type, this isn’t true and so databinding won’t work.


I don’t believe its that simple to stick them in an ObservableCollection bound to a DataGrid because the mechanics of it uses ICustomTypeDescriptor


More to come... (have a train to catch)

Labels: , ,

0 comments:

Post a Comment