Introducing DuckCallLib - An Extension Method to (almost) enable Duck Typing in C#
Scratching an itch today, thinking about code I have written in the past to attempt to do duck calls in C# (that is, call a named method without explicitly knowing that it even supports the method) - I decided, what the heck, why not just write the extension method over object required to do duck calls.
So, with great fanfare (ha!) - I have published DuckCallLib on codeplex (codeplex.com/duckcalllib). This is hardly a big project, more like a handy piece of code that allows you to not have to dig through reflection yourself every time you need to handle a duck typing scenario from C# code.
Let say we have a simple class, such as this:
public class RandomClass
{
public int AddNumbers(int op1, int op2)
{
return (op1 + op2);
}
public double AddNumbers(double op1, double op2)
{
return (op1 + op2);
}
}
Now, lets say we want to call "AddNumbers" without knowing anything about RandomClass:
object rndClass = new RandomClass();
object two = rndClass.DuckCall("AddNumbers", new object[] { 1, 1 }, null);
Assert.IsTrue((int)two == 2);
Or, a more complex and meaningful scenario, we want try to make a call, but have a lambda get invoked if the method is missing:
Func<object,string,object[],object> methodMissingHandler =
(source, methodName, theParameters) =>
(decimal)theParameters[0] +
(decimal)theParameters[1];
object rndClass = new RandomClass();
object two = rndClass.DuckCall(
"AddNumbers",
new object[] { 1m, 1m },
methodMissingHandler );
Assert.IsTrue((decimal)two == 2m);
As you can see, ruby this isn't. It is not nearly as clean syntactically as I would like it to be. However, given the current limitations of the C# language, this is what I have been able to come up with. If anyone has other ideas, I certainly encourage anyone to send em my way.
Enjoy!