Just sharing some of my inconsequential lunch conversations with you... RSS  

Tuesday, August 21, 2007

Duck Typing in C#

Let's be clear about it: there's nothing wrong about Duck Typing, as long as we used it on exceptional cases, and on a controlled environment like the duck typing project.

Here's a sample:


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



Why restrict Duck Typing usage? Because (whenever possible) early interface identification lowers the typing mismatch. In my view, we should privilege early interface definition whenever possible.

No comments:

Development Catharsis :: Copyright 2006 Mário Romano