Mike Taulty's Blog
Bits and Bytes from Microsoft UK
The Strange Case of the RouteValueDictionary

Blogs

Mike Taulty's Blog

Elsewhere

Archives

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.


Posted Tue, Sep 23 2008 10:21 AM by mtaulty
Filed under:

Comments

LA.NET [EN] wrote RouteValueDictionary: abuse or elegance?
on Sat, Oct 4 2008 3:02 PM
Today I was reading an old post by Mike Tauty about the RouteValueDictionary and I remembered some old
ASPInsiders wrote RouteValueDictionary: abuse or elegance?
on Sat, Oct 4 2008 4:12 PM
Today I was reading an old post by Mike Tauty about the RouteValueDictionary and I remembered some old