In playing with ASP.NET routing, I came across this really weird piece of code in a class called RouteValueDictionary which I can reproduce here;
RouteValueDictionary dictionary = new RouteValueDictionary( new { key1 = "value1", key2 = "value2", key3 = "value3" }); foreach (var item in dictionary) { Console.WriteLine("{0} = {1}", item.Key, item.Value); }
I scratched my head over this quite a bit when I first saw it as the usage was as above in that it seemed to be adding a single instance of an anonymous type to a dictionary as a way of populating that dictionary.
It had me wondering
“So, where’s the key coming from and where’s the value coming from?”
You can probably guess that what the constructor for RouteValueDictionary actually does is to reflect on the object that’s passed to it and it turns each property name into a key and each property value into a value in the dictionary.
Is it me – or is this a case of anonymous type abuse? Seems really ugly to me but perhaps there was some devious reason for it? I think I’d have preferred to see the RouteValueDictionary constructor take a IEnumerable<KeyValuePair<string,object>> as that seems a lot more obvious, intuitive, discoverable to me.