Leverage these new features in C# 4.0 to interoperate with new dynamic .NET languages, and simplify your code.

by Joydip Kanjilal

Jun 29, 2009

Page 2 of 3

Dynamic Lookup

The introduction of dynamic types to the Common Type System led directly to one of the great new features added to C# 4.0: You longer need to worry about the type of an object when assigning values returned from methods or expressions; the runtime performs the necessary binding for you according to the returned value's type.

Static and Dynamic Typing

Statically typed languages such as C++, C#, or Java perform type checking at compile time. In contrast, dynamically typed languages such as JavaScript, PERL, and Ruby perform type checks at runtime. C# was originally designed as a language based on strong typing—which is good because the compiler can ensure that types match, catching potential bugs earlier in the development cycle. The change now to include dynamic typing in C# is intended to let you invoke different kinds of objects such as COM, and JavaScript seamlessly.

The var and dynamic keywords

To support dynamic variable declaration, C# 4.0 introduces the dynamic keyword. Both the var and dynamic keywords provide local type inference in C#. You need not specify the data type on the left hand-side of an assignment operator, and the system will bind to the correct type on the fly. However, unlike the dynamic keyword, when you use var you must still specify the type on the right-hand side of an assignment operator. Using the dynamic keyword, you need not specify the type at all: all type binding gets done at runtime.

A Dynamic Typing Example

All this sounds more complicated than it is. Here's an example. Consider the following three business logic classes, each with its own set of methods.

As you can see, each class has distinct methods. Now, suppose you need to invoke the "process" method on instances of any of these classes on the fly. This type of problem is well-suited to dynamic typing. First, create an enum that contains a list of the business logic instance types.