Jerry Nixon @Work: The Dynamic keyword & Expando class in C#4

Jerry Nixon on Windows

Monday, February 15, 2010

The Dynamic keyword & Expando class in C#4

If you have developed in C# then you know all objects can cast down to “object”. Object is the base of all objects.

If want a property value from an object type, you must reflect to it like x.GetType().Properties[“Color”].getValue(x, null). Right?

“Dynamic” objects operate like object, except when you request a property it reflects for you – saving you the reflection. 

And, the big deal here is: there’s no Compile-Time error. You specify dynamic, so the compiler assumes the property exists.

That’s dynamic, so to speak. But be careful. Since you bypass the compiler’s validation, you can create crazy exceptions.

But what if, at RUNTIME, you wanted to reference a class that does not exist? Can you do it? You can with Expando.

Once instantiated, simply attempt to set a property or method on Expando class object and it becomes a fully typed member.

Check out this sample:


Get the code here:

The results would be:

Press any key to continue...