Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference a field in an ExpandoObject dynamically?

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]);
like image 554
ScArcher2 Avatar asked Dec 21 '22 14:12

ScArcher2


1 Answers

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)

like image 77
BrokenGlass Avatar answered Mar 01 '23 18:03

BrokenGlass