deft flux

A portal into the creative workings of David Meyer

About the author

David Meyer (a.k.a. "deft flux") is a software developer fluent in C#, C++, Java and others. He also programs in his spare time and enjoys playing instruments and making electronic music.
E-mail me Send mail

Recent posts

Recent comments

Authors

Disclaimer

The opinions expressed by the author are his alone and do not represent any other person or organization unless stated otherwise. The opinions given in comments are solely those of the person who wrote the comment and are not necessarily the opinions of the author of this site. The author of a post is not responsible for the content of its comments.

© Copyright 2008
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.

    }
}