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]);

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Note that the conversion can be done implicitly: IDictionary<string, object> expandoDict = expando; will work fine.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.