Search code examples
c#language-design

Why doesn't C# let me index into dynamic like a dictionary?


The dynamic keyword in C# will let me do something like this:

dynamic obj = ....;
var foo = obj.foo;

where the property reference obj.foo is resolved at runtime.

Since the property is resolved at runtime, why can't you specify the property itself as a variable? For example,

var propName = "foo";
var foo = obj[propName];

?

I'm aware you can accomplish something like that through reflection or by converting the object to a Dictionary. I'm not interested in the solution as an explanation for why C# doesn't support Javascript-like square bracket lookup in the first place.


Solution

  • One likely reason for why this has not been done is ambiguity.

    Consider this example:

    dynamic d = new Dictionary<string,object>() {
        {"Count", 2}
    };
    object c = d["Count"];
    

    On one hand, the dictionary has property Count, and the dictionary has one entry, so c should be set to 1. On the other hand, the dictionary has an entry for the key "Count", so c should be set to 2.

    Selecting either one of these alternatives would arbitrarily discard the other possibility. In cases like that it is best to not introduce the feature in the first place.