2

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.

wrschneider
  • 17,913
  • 16
  • 96
  • 176

1 Answers1

6

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Interesting. So it wasn't just omitted -- it could actually cause problems. – wrschneider Jul 10 '15 at 01:38
  • @ChrisMarisic You are missing the point: when multiple answers are *possible*, the only way to decide which one of them is "the correct answer" is to *declare* one answer correct, to the exclusion of other possible answers. This choice would be arbitrary no matter how you look at it. – Sergey Kalinichenko Apr 27 '16 at 19:23
  • It would not be arbitrary, an indexer applied to a dynamic should index into the object itself, not invoke any indexer. The lacking of this nearly ruins dynamic in c#. – Chris Marisic Apr 27 '16 at 19:33
  • @ChrisMarisic No matter how strongly you feel about it, your choice is just as arbitrary as its alternative. One could come up with a pretty strong objection to your way of handling this situation by demonstrating that casting `d` back to `IDictionary` and applying the same exact indexer produces a different result. – Sergey Kalinichenko Apr 27 '16 at 20:25
  • @dasblinkenlight i don't agree. – Chris Marisic Apr 28 '16 at 13:57