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

1 dynamic dynamicDictionary = new DynamicDictionary<string>(); 2 dynamicDictionary.cat = "Tom"; 3 4 System.Console.WriteLine(dynamicDictionary.cat);//also prints out "Tom"

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.

1 public class DynamicDictionary<TValue> : DynamicObject 2 { 3 private Dictionary<string, TValue> _dictionary; 4 5 public DynamicDictionary() 6 { 7 _dictionary = new Dictionary<string, TValue>(); 8 } 9 10 public override bool TryGetMember(GetMemberBinder binder, out object result) 11 { 12 TValue data; 13 if (!_dictionary.TryGetValue(binder.Name, out data)) 14 { 15 throw new KeyNotFoundException("There's no key by that name"); 16 } 17 18 result = (TValue)data; 19 20 return true; 21 } 22 23 public override bool TrySetMember(SetMemberBinder binder, object value) 24 { 25 if (_dictionary.ContainsKey(binder.Name)) 26 { 27 _dictionary[binder.Name] = (TValue)value; 28 } 29 else 30 { 31 _dictionary.Add(binder.Name, (TValue)value); 32 } 33 34 return true; 35 } 36 }

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