In the vein of $indexer, make anonymous objects implement IReadOnlyDictionary<string,object>

Topics: C# Language Design
Apr 10, 2014 at 3:34 PM
Edited Apr 10, 2014 at 3:50 PM
The $indexer notation is designed to make it easier to read and write from dictionaries that act like js-style objects. However, the literal syntax for creating a new Dictionary<string,object> is still fairly ugly. And $indexer did not infact change much in the common case. Plus if the name isn't a proper C# identifier or a reserved keyword you still need to invoke it with @ making absolutely ugly identifiers.
old:
return new Dictionary<string,object>{{"projectId",5},{"advisor","Jim Bob"},{"delegate","Eric Smith"}};
new:
return new Dictionary<string,object>{$projectId=5,$advisor="Jim Bob",$@delegate="Eric Smith"};
Not really much of a reduction in characters typed.
We can also use anonymous objects
return new {projectId=5,advisor="Jim Bob",@delegate="Eric Smith"};
However, to actually use the anonymous object outside of where its declared, you either must use dynamic or reflection to get to the properties and their values. If the library you are using does not support them you must turn turn the object into a dictionary.This is somewhat annoying. What would be ideal is if they also implemented IReadOnlyDictionary<string,object>. That way for dynamic users who are outside of the assembly or scope of declaration can also access the object's properties without resorting to reflection or dynamic.

If there is concern of breaking or changing existing behavior perhaps a new syntax is in order, maybe if you prefix the keys with a $, or if we put a $ before the open curly brace. That way compatibility will be preserved, and we get a short hand for dictionary literals in C#.

Edit: I would recommend it as Explicit implementation, so you would never opt-in to dictionary features unless you cast it.
Apr 10, 2014 at 6:31 PM
My concern would be breaking all anonymous classes on platforms without generics...
Apr 11, 2014 at 5:20 PM
What do you mean? Anonymous classes in full .net are implemented as generic types with each property type being declared as generic. (e.g. T projectId, T2 advisorId)

I didn't realize the micro framework supported anonymous classes. But if it does then a simple fix is to implement just IDictionary (I don't know if there exists an IReadOnlyDictionary).
Apr 11, 2014 at 6:50 PM
Indeed. The feature set that actually doesn't require generics is surprisingly large, but anonymous classes are not on this party, sorry!
Apr 12, 2014 at 4:24 PM
I also vote for this (actually I proposed same thing some time ago at https://roslyn.codeplex.com/discussions/541304, but this one seems to get more attention).