Im trying to use DynamicObject in c#, and I needed an array of dynamic:
var d = new dynamic[];
which works fine.
EDIT : See ExpandoObject below.
But I also like to fill that array with some data with this compressed initialize new syntax:
var d = new dynamic[] {
new {
Name = "Some",
Number = 1010
},
new {
Name = "Other",
Number = 2010
}
}
But in that case all objects gets the non-dynamic type "object" and a loop through the items 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 just initialize the array items the wrong way. How to add dynamic objects instead?
EDIT: New content:
I realize "dynamic" does not have the capability to dynamically add properties.
I better be using ExpandoObject which exposes all items in an an internal dictionary as properties. But unfortunately ExpandoObject does not seem to support this nice compressed create syntax, and the compiler complains:
var d = new ExpandoObject[]{
new ExpandoObject(){
Name="Nnn",
Number=1080
}
}
So the answer might just be : it's not possible.
Hopefully you do not really need dynamics
class Program
{
static void Main(string[] args)
{
var d = new[]
{
new
{
Name = "Some",
Number = 1010
},
new
{
Name = "Other",
Number = 2010
}
};
foreach (var item in d)
{
string s = @item.Name;
int n = @item.Number;
Console.WriteLine("{0} {1}", s, n);
}
}
}
I come a bit late but here is what i found about it :
if I can't initialise an ExpandoObject, how about initialising it with a dynamic type ?
so i did the following extension method
public static ExpandoObject CreateExpando(this object item)
{
var dictionary = new ExpandoObject() as IDictionary<string, object>;
foreach (var propertyInfo in item.GetType().GetProperties())
{
dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(item, null));
}
return (ExpandoObject)dictionary;
}
I know it's far from ideal, but it's the best I could achieve for now, it works like this :
var myExpandoObject = new { Name="Alex", Age=30}.CreateExpando();
The open source framework Impromptu-Interface has a compressed initialization syntax that works with ExpandoObject.
dynamic @new = Builder.New<ExpandoObject>();
var d = @new.List(
@new.Expando(
Name:"Some",
Number: 1010
),
@new.Expando(
Name:"Other",
Number: 2010
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With