How can I refer to a field in ExpandoObject dynamically?

Is there a way to dynamically access the expando property by searching for the "IDictionary" style?

var messageLocation = "Message"; dynamic expando = new ExpandoObject(); expando.Message = "I am awesome!"; Console.WriteLine(expando[messageLocation]); 
+4
source share
1 answer

You need to drop 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 should be printed as dynamic , so access to the properties is determined at runtime - otherwise your sample will not compile)

+11
source

All Articles