ILoggable

A place to keep my thoughts on programming

January 22, 2010 .net, geek , , ,

Duckpond: Lightweight duck-typing for C#

Edit: Changed As to AsImplementationOf since it’s an extension method on object and too likely to collide.

A while back I was talking about Interface Segregation and proposed using either LinFu’s DynamicObject or delegate injection. While I played a bit more with delegate injection, in practical use delegate injection turned out to be rather ugly and not really improve readability.

So, I’ve come back to wanting to cast an object to an interface regardless of what interfaces that object implemented. I wanted this to be as simple and lightweight as possible, so rather than using a dynamic proxy framework, i simply rolled my own IL and wrote a pure proxy that does nothing but call the identical method on the class it wraps.

Introducing DuckPond

DuckPond is a very simple and focused library. It currently adds only a single extension method: object.AsImplementationOf<Interface>

Given a class Duck that implements a number of methods, including Quack:

public class Duck {
  public void Quack(double decibels) {
    ...
  }

  //... various other methods ...
}

we can easily cast Duck to a more limited interface that the class doesn’t implement such as:

public interface IQuacker {
  void Quack(double decibels);
}

using the object.AsImplementationOf<T> extension method:

using Droog.DuckPond;

...

var quacker = new Duck().AsImplementationOf<IQuacker>();

That’s all there is to it.

But is it fast?

Honestly, i don’t know yet. I have not benchmarked the generated classes against virtual method dispatches or LinFu’s and Castle’s dynamic proxy. I assume it is, since unlike with dyanmic proxy, DuckPond doesn’t use an interceptor. Instead it emits Intermediate Language for each call in the interface, dispatching the call against the wrapped instance’s counterpart.

Try it, fork it, let me know what you think

The code is available now at GitHub: http://github.com/sdether/duckpond

3 to “Duckpond: Lightweight duck-typing for C#”

Trackbacks/Pingbacks

  1. […] object and use it anywhere that expects a typed class, regardless of its capabilities. I wrote Duckpond for C# to only address casting classes to interfaces that they satisfy, but I should extend it to […]

  2. […] I solved half of this problem with Duckpond: […]

  1. Anonymous says...

    Love it!

  2. Promise: Classes aren’t Types says...

    […] object and use it anywhere that expects a typed class, regardless of its capabilities. I wrote Duckpond for C# to only address casting classes to interfaces that they satisfy, but I should extend it to […]

  3. Ducks Unlimited says...

    […] I solved half of this problem with Duckpond: […]

Leave a comment