Jahamal’s answer doesn’t say why you get the error. The reason is that the anonymous class is internal to the assembly. Keyword dynamic doesn’t allow you to bypass member visibility.
The solution is to replace the anonymous class with named public class.
Here’s another good example explaining the reason and another possible solution.
The reason the call to
data2.Personfails is that the type information ofdata2is not available at runtime. The reason it’s not available is because anonymous types are not public. When the method is returning an instance of that anonymous type, it’s returning aSystem.Object which references an instance of an anonymous type – a type whose info isn’t available to the main program. The dynamic runtime tries to find a property calledPersonon the object, but can’t resolve it from the type information it has. As such, it throws an exception. The call todata.Nameworks fine sincePersonis a public class, that information is available and can be easily resolved.
This can affect you in any of the following cases (if not more):
- You’re returning a non-public, non-internal type using
System.Object.
2. You’re returning a non-public, non-internal derived type via a public base type and accessing a property in the derived type that’s not in the base type.
3. You’re returning anything wrapped inside an anonymous type from a different assembly.