I'm writing a simple wrapper to "duck" a dynamic
object against a known interface:
interface IFoo { string Bar(int fred); }
class DuckFoo : IFoo
{
private readonly dynamic duck;
public DuckFoo(dynamic duck)
{
this.duck = duck;
}
public string Bar(int fred)
{
return duck.Bar(fred);
}
}
This works fine if the dynamic
object can respond to the Bar
signature. But if it cannot this fails only when I call Bar
. I would prefer if it could fail faster, i.e., with argument validation upon construction of the DuckFoo
wrapper. Something like this:
public DuckFoo(dynamic duck)
{
if(/* duck has no matching Bar method */)
throw new ArgumentException("duck", "Bad dynamic object");
this.duck = duck;
}
In Ruby there is a respond_to?
method that can be used to test if an object "has" a certain method. Is there a way to test that with dynamic objects in C# 4?
(I am aware that even with this check the Bar call could fail later on because the dynamic nature of the duck
lets it stop responding to methods later on.)