I am trying to use DynamicObject in C # and I need an array of dynamic:
var d = new dynamic[];
which works great.
EDIT: see the ExpandoObject section below.
But I also like to populate this array with some data using this compressed new syntax:
var d = new dynamic[] { new { Name = "Some", Number = 1010 }, new { Name = "Other", Number = 2010 } }
But in this case, all objects get the non-dynamic type "object", and a loop through the elements will give me an exception:
foreach (dynamic item in d) { @item.Name @item.Number }
Error: "object" does not contain a definition for "Name". I guess I'm just initializing the elements of the array in the wrong way. How to add dynamic objects?
EDIT: New Content:
I understand that βdynamicβ does not have the ability to dynamically add properties.
It is better to use ExpandoObject, which exposes all the elements in the internal dictionary as properties. But unfortunately, ExpandoObject does not seem to support this beautiful, compressed creation syntax, and the compiler complains:
var d = new ExpandoObject[]{ new ExpandoObject(){ Name="Nnn", Number=1080 } }
So the answer may be simple: it is not possible.
joeriks
source share