In C#, how do I remove a property from an ExpandoObject?

Matt Cashatt picture Matt Cashatt · Jan 24, 2013 · Viewed 27.9k times · Source

Say I have this object:

dynamic foo = new ExpandoObject();
foo.bar = "fizz";
foo.bang = "buzz";

How would I remove foo.bang for example?

I don't want to simply set the property's value to null--for my purposes I need to remove it altogether. Also, I realize that I could create a whole new ExpandoObject by drawing kv pairs from the first, but that would be pretty inefficient.

Answer

Jon picture Jon · Jan 24, 2013

Cast the expando to IDictionary<string, object> and call Remove:

var dict = (IDictionary<string, object>)foo;
dict.Remove("bang");