Skip to content

Cannot access anonymous class in properties of dynamic object #93

@NielsUll

Description

@NielsUll

Accessing a property of an anonymous class fails when going through a dynamic object:

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

[Test]
public void Get_Property_of_a_nested_anonymous()
{
    dynamic dyn = new ExpandoObject();
    dyn.Sub = new { Foo = "bar"};
    var interpreter = new Interpreter()SetVariable("dyn", (object)dyn);
    Assert.AreEqual(dyn.Sub.Foo, interpreter.Eval("dyn.Sub.Foo"));
}

It works fine when the class is named: dyn.Sub = new MyClass() { Foo = "bar"};
It also works if we introduce an intermediate variable:

    dynamic dyn = new ExpandoObject();
    dyn.Sub = new { Foo = "bar"};
    var interpreter = new Interpreter().SetVariable("dyn", dyn);
    interpreter.SetVariable("sub", interpreter.Eval("dyn.Sub"));
    Assert.AreEqual(dyn.Sub.Foo, interpreter.Eval("sub.Foo"));

Aslo discussed on stack overflow: https://stackoverflow.com/questions/53040955/how-can-i-use-dynamic-variables-with-anonymous-types

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions