Tag Archives: C# dynamic

Creating a Dynamic Dictionary with C# 4 dynamic

In C# 4 there’s a new keyword introduced which is dynamic.

Here’s what msdn say about it

The dynamic type enables the operations in which it occurs to bypass

compile-time type checking. Instead, these operations are resolved at

run time.

combined with the var keyword.. anonymous method, and don’t forget anonymous object. I couldn’t help get the feeling that coding in C# is getting similar in a way coding in javascript Smile.

Right, let’s get back to the topic,  so I want to create a dynamic dictionary which enable me from doing this

to this

This is surprisingly quite easy to implement, as all we need to is extend our class from DynamicObject that reside in System.Dynamic and override couple of methods..two actually.

The trick is in the TryGetMember and TrySetMember method which set and get the property for dynamic object. There’s other method in DynamicObject that you can override such TryGetIndex and TrySetIndex which try to access the dynamic object by index.

You can read more about it in Aaron’s blog