BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News C# Feature Focus: Dynamically Typed Objects, Duck Typing, and Multiple Dispatch

C# Feature Focus: Dynamically Typed Objects, Duck Typing, and Multiple Dispatch

This item in japanese

Before we dig into the first C# feature, let it be known that Microsoft has promised that any capability found in C# will be offered in VB and vice versa in some fashion. However, they will not necessarily offer it the same way and the languages are expected to continue to diverge.

With the increasing importance of dynamic languages and the DLR, C# needs to be able to work with dynamically typed objects. Currently it is possible to make late bound calls via reflection for static classes, but this takes a lot of code. Moreover, calls to DLR objects require an entirely different call using the DLR's reflection libraries.

In C#, you simply declare the object's static type as "dynamic". Like VB's Option Explicit Off, this tells the compiler to emit the necessary code to resolve the method binding at runtime calls. At the IL, variables declared as dynamic are really of type System.Object with an additional tag indicating it uses dynamic calling semantics.

At runtime all of the normal overload resolution rules work against the object's runtime type. This means you get the ability to perform multiple dispatch directly instead of jumping through reflection or using visitor patterns.

Each dynamic language has its own rules for member lookup. To support this object can implement the IDynamicObject interface. If it exists on the runtime object, the object gets to handle its own member lookup. In the demonstration, Anders showed how to define a dynamic object in C# itself.

And of course, all this means you can use duck typing wherever you want in C#.

Rate this Article

Adoption
Style

BT