Duck type testing with C# 4 for dynamic objects
I’m wanting to have a simple duck typing example in C# using dynamic objects. It would seem to me, that a dynamic object should have HasValue/HasProperty/HasMethod methods with a single string parameter for the name of the value, property, or method you are looking for before trying to run against it. I’m trying to avoid try/catch blocks, and deeper reflection if possible. It just seems to be a common practice for duck typing in dynamic languages (JS, Ruby, Python etc.) that is to test for a property/method before trying to use it, then falling back to a default, or throwing a controlled exception. The example below is basically what I want to accomplish.
If the methods described above don’t exist, does anyone have premade extension methods for dynamic that will do this?
Example: In JavaScript I can test for a method on an object fairly easily.
//JavaScript
function quack(duck) {
if (duck && typeof duck.quack === "function") {
return duck.quack();
}
return null; //nothing to return, not a duck
}
How would I do the same in C#?
//C# 4
dynamic Quack(dynamic duck)
{
//how do I test that the duck is not null,
//and has a quack method?
//if it doesn't quack, return null
} 

scott on May 20, 2012
Try this:
Or this (uses only dynamic):
fernando-correia on May 20, 2012
If you have control over all of the object types that you will be using dynamically, another option would be to force them to inherit from a subclass of the
DynamicObjectclass that is tailored to not fail when a method that does not exist is invoked:A quick and dirty version would look like this:
You could then do the following:
And your output would be:
Edit: I should note that this is the tip of the iceberg if you are able to use this approach and build on
DynamicObject. You could write methods likebool HasMember(string memberName)if you so desired.scott on May 20, 2012
The shortest path would be to invoke it, and handle the exception if the method does not exist. I come from Python where such method is common in duck-typing, but I don’t know if it is widely used in C#4…
I haven’t tested myself since I don’t have VC 2010 on my machine
bhtpjogetu on May 20, 2012
Implementation of the HasProperty method for every IDynamicMetaObjectProvider WITHOUT throwing RuntimeBinderException.
pharme86 on May 20, 2012
Here’s an article that shows how to do duck typing using LinFu:
http://plaureano.blogspot.com/2011/04/duck-typing-with-linfu-c-40s-dynamic.html
Try it out and let me know if helps.
johan-offer on May 20, 2012
http://code.google.com/p/impromptu-interface/ Seems to be a nice Interface mapper for dynamic objects… It’s a bit more work than I was hoping for, but seems to be the cleanest implementation of the examples presented… Keeping Simon’s answer as correct, since it is still the closest to what I wanted, but the Impromptu interface methods are really nice.