4

Is there a way to dynamically access the property of an expando using a "IDictionary" style lookup?

var messageLocation = "Message";
dynamic expando = new ExpandoObject();
expando.Message = "I am awesome!";
Console.WriteLine(expando[messageLocation]);
dbc
  • 104,963
  • 20
  • 228
  • 340
ScArcher2
  • 85,501
  • 44
  • 121
  • 160

1 Answers1

11

You have to cast the ExpandoObject to IDictionary<string, object> :

var messageLocation = "Message";
dynamic expando = new ExpandoObject();
expando.Message = "I am awesome!";

var expandoDict = (IDictionary<string, object>)expando;
Console.WriteLine(expandoDict[messageLocation]);

(Also your expando variable must be typed as dynamic so property access is determined at runtime - otherwise your sample won't compile)

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 6
    Note that the conversion can be done implicitly: `IDictionary expandoDict = expando;` will work fine. – Jon Skeet May 05 '11 at 20:25
  • 2
    Thanks for the info. I really really wish i could just say expando["whatever"] though. I don't really understand why the cast is necessary especially since it is dynamic. – ScArcher2 May 05 '11 at 20:35