Here are a couple basic examples of using the duck typing library.
Interface Casting
Here we will cast a class called MyAdder to an interface called ICanAdd.
public interface ICanAdd
{
int Add(int x, int y);
}
public class MyAdder
{
public int Add(int x, int y)
{
return x + y;
}
}
public class Program
{
void Main()
{
MyAdder myAdder = new MyAdder();
ICanAdd adder = DuckTyping.Cast<ICanAdd>(myAdder);
int sum = adder.Add(2, 2);
}
}
Delegate Casting
Two delegates with compatible method parameters and return types can be casted to one another:
public delegate void Action(object x);
public delegate void StringAction(string s);
public class Program
{
private void MyStringAction(string s)
{ ... }
void Main()
{
StringAction stringAction = new StringAction(this.MyStringAction);
Action action = DuckTyping.Cast<Action>(stringAction);
action("String value.");
action(1);
StringAction stringAction2 = DuckTyping.Cast<StringAction>(action);
}
}