Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing safe duck-typing in C#

After looking at how Go handles interfaces and liking it, I started thinking about how you could achieve similar duck-typing in C# like this:

var mallard = new Mallard(); // doesn't implement IDuck but has the right methods
IDuck duck = DuckTyper.Adapt<Mallard,IDuck>(mallard);

The DuckTyper.Adapt method would use System.Reflection.Emit to build an adapter on the fly. Maybe somebody has already written something like this. I guess it's not too different from what mocking frameworks already do.

However, this would throw exceptions at run-time if Mallard doesn't actually have the right IDuck methods. To get the error earlier at compile time, I'd have to write a MallardToDuckAdapter which is exactly what I'm trying to avoid.

Is there a better way?

edit: apparently the proper term for what I call "safe duck-typing" is structural typing.

like image 660
Wim Coenen Avatar asked Nov 13 '09 17:11

Wim Coenen


1 Answers

How can you know if a cow walks like a duck and quacks like a duck if you don't have a living, breathing cow in front of you?

Duck-typing is a concept used at run-time. A similar concept at compile-time is structural typing which is AFAIK not supported by the CLR. (The CLR is centred around nominative typing.)

[A structural type system] contrasts with nominative systems, where comparisons are based on explicit declarations or the names of the types, and duck typing, in which only the part of the structure accessed at runtime is checked for compatibility.

The usual way to ensure that duck-typing throws no exception at run-time are unit-tests.

like image 137
dtb Avatar answered Oct 13 '22 10:10

dtb