C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly

I believe the problem is that the anonymous type is generated as internal, so the binder doesn’t really “know” about it as such.

Try using ExpandoObject instead:

public static dynamic GetValues()
{
    dynamic expando = new ExpandoObject();
    expando.Name = "Michael";
    expando.Age = 20;
    return expando;
}

I know that’s somewhat ugly, but it’s the best I can think of at the moment… I don’t think you can even use an object initializer with it, because while it’s strongly typed as ExpandoObject the compiler won’t know what to do with “Name” and “Age”. You may be able to do this:

 dynamic expando = new ExpandoObject()
 {
     { "Name", "Michael" },
     { "Age", 20 }
 };
 return expando;

but that’s not much better…

You could potentially write an extension method to convert an anonymous type to an expando with the same contents via reflection. Then you could write:

return new { Name = "Michael", Age = 20 }.ToExpando();

That’s pretty horrible though 🙁

Leave a Comment