32

Is there a way to add a property to an ExpandoObject with the same name as a string value?

For example, if I have:

string propName = "ProductNumber";
dynamic obj = new System.Dynamic.ExpandoObject();

I can create the property ProductNumber like:

obj.ProductNumber = 123;

But, can I create the property obj.ProductNumber based on the string propName? So, if I don't know what the name of the property will be in advanced, I can create it based on this input. If this is not possible with ExpandoObject, any other areas of C# I should look into?

Paul
  • 3,725
  • 12
  • 50
  • 86
  • 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
  • Practical use of the above found here: http://stackoverflow.com/questions/2974008/adding-unknown-at-design-time-properties-to-an-expandoobject – Nic Aug 05 '14 at 14:41

2 Answers2

44

ExpandoObject implements IDictionary<string, object>:

((IDictionary<string, object>)obj)[propName] = propValue

I don't know off the top of my head whether you can use the indexer syntax with a dynamic reference (i.e., without the cast), but you can certainly try it and find out.

phoog
  • 42,068
  • 6
  • 79
  • 117
  • 1
    you can't index an ExpandoObject as you've done in your first example – Mike Corcoran Apr 06 '12 at 19:52
  • 1
    Second example is good. First example gives `Cannot apply indexing with [] to an expression of type 'System.Dynamic.ExpandoObject'` – Paul Apr 06 '12 at 19:53
  • 1
    @Paul thanks -- I had forgotten that the indexer is an explicit interface implementation. Answer edited. – phoog Apr 06 '12 at 20:00
  • @VBRonPaulFan yes, I had forgotten that the interface implementation is explicit. I've edited the answer. – phoog Apr 06 '12 at 20:03
  • 1
    man, i am so glad i found this post. i was about to implement some object off of DynamicObject from some other tutorials just to get this ability. life and time saver thanks!! :D – Tony Nov 06 '13 at 22:53
20

Cast the ExpandoObject to an IDictionary<string,object> to do this:

string propName = "ProductNumber";
dynamic obj = new System.Dynamic.ExpandoObject();
var dict = (IDictionary<string,object>)obj;
dict[propName] = 123;
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 1
    +1 for at least mentioning that `ExpandoObject` is `IDictionary` underneath. [See docs](http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx) – Joseph Yaduvanshi Apr 06 '12 at 19:49