Category Archives: .NET 4

Parsing an xml to get a c# object with dynamic type

Standard

Okay, okay you’re right, thank you Leo 😉 So let’s render unto Caesar the things which are Caesar’s… Microsoft took into account the power of those weakly-typed languages such as JavaScript, the ones which allow you to deal with types you don’t know yet. Within .NET 4, they release the dynamic type, in reference to those languages, which they specifically call dynamic languages.

So now, if you derive from DynamicObject to create your own one, you can use pretty much the same code I used previously in JavaScript to get a c# object from Xml. You can create any property you’d like at runtime, only by accessing it like an array. Just write myDynamic[“house”]=whatever and it gets created in the meantime. In the end, you’ll be able to access any property you created in a totally transparent manner like myDynamic.house….

Plus, with the

TryConvert(ConvertBinder binder, out object result)

you can get the statically typed object you were expecting if you ever need a strongly typed object.

Enough of this talking, here you can find some more explanations about dynamic and how to take advantage of it :
http://msdn.microsoft.com/en-us/library/dd233052.aspx
http://msdn.microsoft.com/en-us/library/dd264736.aspx
http://msdn.microsoft.com/en-us/library/dd264741.aspx

and here’s the code:
https://docs.google.com/open?id=0BwW7tKeWhpnKcFZUakpJVENvOWs