Home of the AlmostImplementedException

Lets get dynamic with ExpandoObject

With .Net 4 Microsoft introduced the ExpandoObject (funny name). With this object you can dynamically add and remove properties. Thats very useful to get rid of this ugly CleanCode you produce every time ;-).
Seriously, don’t use this class except for very special occasions, like producing a dynamic object where you don’t care what properties it has. For example for serialization or deserialization of Json-objects.
In any other case, its a very bad idea to use ExpandoObject.
And if you need a reason why not to use it, here are 3 =>
– nobody knows which properties are there or what to do with the object and
– nobody knows the datatype of a property and
– if you use a nonexisting property you’ll get an exception. At runtime.

But anyway here is a simple example how to use it:

As you can see, the usage of ExpandoObject is very simple. But if you use it wrong you’ll get in big trouble. Just try to get the property Year of member1 or work with the different datatypes of Age.

But ok it’s dynamic and you want to use it. And as i mentioned, for de/serialization its ok. Maybe you just want a dynamic Json-String. Then just use the Json.Net library and call
JsonConvert.SerializeObject(member2);. Thats all you need to get your Json created.

You can even use a List as a parameter:

And of course you can use a List of dynamic instead of String.

Another rather funny part is the deletion of a property. In C# and VB there is no direct way, so you seriously have to cast your dynamic to (IDictionary) and call Remove like in this example:

But with this in mind you also can iterate through all the properties:

Conclusion: ExpandoObject is a nice way to create a dynamic object, if you know where and how to use it safely.
I don’t recommend it, but sometimes you have to.

Share :

Leave a Reply