Download the source: blogducktypingreloaded.zip
It's time to do an update on my blog post from the end of 2008, when I did take a first look at the dynamic capabilities in .NET 4.0. From the beta to the final version of 4.0 they did unfortunatelly change the API used for dynamic dispatching and dynamic objects. Instead of MetaObject and IDynamicObject all we need in the updated version of the API is System.Dynamics.DynamicObject. It takes the place of IDynamicObject and MetaObject is gone for good.
This makes it really pleasently easy to implement the same behaviour as I did years ago:
- public class Duck : DynamicObject
- {
- public override bool TryGetMember(GetMemberBinder binder, out object result)
- {
- string resultString;
- var didWork = TryGetMember(binder.Name, out resultString);
- result = resultString;
- return didWork;
- }
- private bool TryGetMember(string name, out string result)
- {
- return dictionary.TryGetValue(name, out result);
- }
- public override bool TrySetMember(SetMemberBinder binder, object value)
- {
- return TrySetMember(binder.Name, value);
- }
- private bool TrySetMember(string name, object value)
- {
- try
- {
- dictionary[name] = value == null ? null : value.ToString();
- return true;
- }
- catch
- {
- return false;
- }
- }
- public override bool TryConvert(ConvertBinder binder, out object result)
- {
- try
- {
- result = Generator.GenerateProxy(binder.Type, this);
- return true;
- }
- catch
- {
- result = null;
- return false;
- }
- }
- }
This is a dynamic Duck that can store any value when given via Property and will return the same value as a string when asked for it via the dynamic keyword.
- d.Test = i;
- dynamic a = d.Test;
- Console.WriteLine(a);
- Console.WriteLine(a.GetType().FullName + " (Should be System.String)");
When you download the sample you can see that the code also includes the ability to do a cast from the dynamic Duck to any given interface, in this case an IQuack. So now the totally dynamic property bag is usable via a strongly typed interface!
Download the source: blogducktypingreloaded.zip
