deft flux

A portal into the creative workings of David Meyer

Duck Typing Examples

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);
}

// Note that MyAdder does NOT implement ICanAdd, 
// but it does define an Add method like the one in ICanAdd:

public class MyAdder
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

public class Program
{
    void Main()
    {
        MyAdder myAdder = new MyAdder();

        // Even though ICanAdd is not implemented by MyAdder, 
        // we can duck cast it because it implements all the members:

        ICanAdd adder = DuckTyping.Cast<ICanAdd>(myAdder);

        // Now we can call adder as you would any ICanAdd object.
        // Transparently, this call is being forwarded to 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.");  // This will call MyStringAction with a string parameter.
        action(1);  // This will compile, because Action takes an object parameter,
                    // but it will throw an InvalidCastException.


        StringAction stringAction2 = DuckTyping.Cast<StringAction>(action);
        // stringAction2 is actually equal to stringAction, since action is uncasted before
        // it tries to cast to StringAction.

    }
}