Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Duck Typing Using Runtime Code Generation

Duck Typing Using Runtime Code Generation

This item in japanese


Duck typing techniques can be used in statically typed languages like C#, but it generally requires some tedious reflection code. But seeing the benefit of such techniques, some are turning to it anyways and are developing ways to make it less painful.

The concept behind duck typing, also known as late binding, is pretty simple; if an object responds to all the methods a function is expected to call, that object can be passed to the function. Those more familiar with static typing may say, "Well isn't that just an Interface?" Well yes and no, while conceptually it is like an Interface, it does not have to be statically defined. This is a big deal when the class is not created by the developer using it.

One option always available is to create an adapter class. The adapter implements the interface and passes the method calls unto the real object. Unfortunately, building these adapter classes is tedious. In order to make this less tedious and more flexible, developers are starting to turn to runtime code generation.

Examples of this can be seen in several open source projects including:

These may end up being stop-gap measure. Visual Basic already has duck typing via Option Strict Off. Dynamically implied interfaces were also considered for VB 9, and though it didn’t make the cut we may see it in VB 10. Meanwhile C# is considering adding a dynamic keyword to gain the same effect as Option Strict Off.

Rate this Article


Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

  • do byte code enhancement instead of reflection

    by Roger Voss,

    Your message is awaiting moderation. Thank you for participating in the discussion.

    reflection is slow

    do byte code enhancement, ala the zillion of tools, libraries, frameworks, and compilers that have done this for years with Java

    for instance, with AspectJ, one can do compile-time enhancement of classes where weaving of aspects happens then

    or weaving can be done at class load time

    in either case, the byte code is edited and the resulting enhanced byte code is used for actual execution

    and of course practically anything can be done and generated by such technique - including generating duck-type interfaces at runtime

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p