DynamicDuck: Duck Typing in a Dynamic World
When dynamics came to C#, I hoped that we'd be able to use interfaces to bridge the gap between dynamic & static typing.
For example, the following really should just work:
It compiles just fine, but you get the following at runtime:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'The best overloaded method match for 'DynamicDuck.Sample.AddUser(DynamicDuck.IUser)' has some invalid arguments'
Well, this just makes me grumpy. So either I'm missing something...which is always possible. (If so, please let me know!) Or this just isn't possible in C# 4.0. Working under the assumption that it isn't possible, I started looking into Duck Typing. I wasn't able to find anyone who had created a Duck Type Library for dynamics, so I took the DuckTaper source and retrofitted it to work with dynamics.
So, when you apply the DynamicDuck this code works.
How does it work? DynamicDuck creates a class that implements the interface and proxies the calls back to the dynamic object. The current duck typing code currently just handles properties, but could be enhanced to support methods in the future.
This functionality works perfectly for DTOs and marshaling data between JSON, XML, or dynamic languages.
Hopefully, this will just be "included" with .NET in the future. But until then...there is DynamicDuck!
[ Download the source ]