Dynamically adding properties to an ExpandoObject

Craig picture Craig · Feb 8, 2011 · Viewed 114.6k times · Source

I would like to dynamically add properties to a ExpandoObject at runtime. So for example to add a string property call NewProp I would like to write something like

var x = new ExpandoObject();
x.AddProperty("NewProp", System.String);

Is this easily possible?

Answer

Stephen Cleary picture Stephen Cleary · Feb 8, 2011
dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);