How can I use dynamic variables with anonymous types?

258 Views Asked by At

I am trying to use dynamic variables containing anonymous types. For example:

var hello = new { french = "bonjour" };
// alternative, dynamic hello
// var hello = new ExpandoObject();
// hello.french = hello

dynamic x = new ExpandoObject();
x.a = hello;

// alternative, anonymous x
// var x = new { a = hello };

Assert.AreEqual("bonjour", x.a.french); // Sanity check - never fails

var interpreter = new Interpreter();
interpreter.SetVariable("x", x);

var result = interpreter.Eval<string>("x.a.french"); // fails
Assert.AreEqual("bonjour", result);

However, I get the error

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'french'

So apparently, x.a does not have the correct type? If I introduce a named class, Translate, and change the first line to

var hello = new Translate {french = "bonjour"};

it works as expected. It also works if I replace make both x and hello anonymous by replacing lines 2 and 3 with

var x = new { a = hello };

or if I make both x and hello dynamic.

If I make x anonymous and hello dynamic, it also fails:

    dynamic hello = new ExpandoObject();
    hello.french = "bonjour";
    var x = new { a = hello} ;

Here, I get the error

DynamicExpresso.Exceptions.ParseException: No property or field 'french' exists in type 'Object'

Is there any way to make my first code sample work? In real life, I am trying something somewhat more complex.

I also have problems trying to access arrays:

dynamic dyn = new ExpandoObject();

dyn.Foo = new int[] {42};
var interpreter = new Interpreter()
            .SetVariable("dyn", (object)dyn);

Assert.AreEqual(dyn.Foo[0], interpreter.Eval("dyn.Foo[0]"));
0

There are 0 best solutions below