BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

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

Adoption
Style

BT