Array of dynamic | ExpandoObject | with a compressed initialize syntax

joeriks picture joeriks · Jan 26, 2011 · Viewed 14.5k times · Source

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.

Answer

Snowbear picture Snowbear · Jan 26, 2011

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);
        }
    }
}