6

Normally, we can create properties like this,

dynamic expando = new ExpandoObject();
expando.Price = 45k;
expando.Value = "Good";

In my case, I won't know the properties such as "Price" or "Value" until runtime. How, can I create such dynamic properties. Something like,

dynamic expando = new ExpandoObject();
expando[properties[0]] = 45k;
expando[properties[1]] = "Good";
expando[properties[2]] = "Red";
expando[properties[3]] = 8;

Anyway to achieve this kind of behavior.

dbc
  • 104,963
  • 20
  • 228
  • 340
Prince Ashitaka
  • 8,623
  • 12
  • 48
  • 71
  • possible duplicate of [Adding unknown (at design time) properties to an ExpandoObject](http://stackoverflow.com/questions/2974008/adding-unknown-at-design-time-properties-to-an-expandoobject) – stijn Jun 11 '13 at 17:08

1 Answers1

20

Just use the fact that it implements IDictionary<string, Object>:

IDictionary<string, Object> expando = new ExpandoObject();
expando[properties[0]] = 45;
expando[properties[1]] = "Good";
expando[properties[2]] = "Red";
expando[properties[3]] = 8;

dynamic d = expando;
// Now use the properties as normal

On the other hand, if you don't know the properties until execution time, what's actually going to consume them? It may still make sense to use ExpandoObject - but equally it may make sense to use Dictionary<string, object> to start with.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks for suggestion. I have AdomdDataReader object. Since, no Grid controls support AdomdData objects to be bound as ItemsSource, I would like to generate a lighter enumerable source from the ADR. For that I was looking into dynamics, since most of the grid controls supports dynamic binding. Thanks again. – Prince Ashitaka Mar 15 '11 at 11:22
  • +1, especially for pointing out that it may be stupid to use ExpandoObject in this case. Currently refactoring my code to use a plain Dictionary instead. :) – Per Lundberg Nov 28 '13 at 08:22