I can’t get dynamic objects to work in types in other assemblies. To replicate this, create a new solution, add a class library, add a console application, add a reference to the class library to the console application, create this class in the class library:
public class DynamicTest
{
public dynamic People { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
foreach (var person in People)
{
sb.AppendLine(person.Name);
}
return sb.ToString();
}
}
And insert this into the console application’s Program.Main():
var test = new DynamicTest
{
People = new[] {
new { Name = "John" },
new { Name = "Jane" }
}
};
Console.WriteLine(test.ToString());
Console.ReadLine();
Run the console application. On the sb.AppendLine line in the DynamicTest class, a RuntimeBinderException is thrown with the message 'object' does not contain a definition for 'Name'.
If I move the DynamicTest class into the console application assembly it works as expected. Is there a limitation with using dynamic across assemblies? This seems to be a pretty reasonable use case for dynamic.
The general consensus for this is to use an ExpandoObject – which is the equivalent that can cross app boundaries.
EDIT: Man, I forgot how the compiler treated
dynamicuntil now.. it’s fascinating.