Array of dynamic | ExpandoObject | with compressed initialization syntax

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.

+7
source share
3 answers

I'm a little late, but here is what I found about it:

if I cannot initialize ExpandoObject, how about initializing it with a dynamic type?

so I made 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 that this is far from ideal, but this is the best that I could achieve at the moment, it works as follows:

 var myExpandoObject = new { Name="Alex", Age=30}.CreateExpando(); 
+4
source

I hope you do not need a speaker.

 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); } } } 
+6
source

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 ) ); 
+1
source

All Articles