C# 4.0 – Part 1 – Dynamic Binding

Most useful language features

 

Dynamic language features. More and more support for Python and Ruby. Also useful for Microsoft Office Automation.

 

"Dynamic" is a type.

 

When do you need this stuff?

 

When you call an api and you don't know what type of object is coming back. You want to be able to use regular C# syntax, especially if you are working with Office or COM, where objects come back weakly typed, lending to ugly syntax, which require casting.

 

The Main Point

 

Good looking code that does not need a lot of casting.

 

Here is what we want to do to talk to a Python Script

 

Calculator calc = GetCalculator();

int sum = calc.Add(10, 20);

 

Here is what we do with C# 3.0

 

object calc = GetCalculator();

Type calcType = calc.GetType();

object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null,

new object[] { 10, 20 });

int sum = Convert.ToInt32(res);

 

This is how C# 4.0 will allows us to work – using the "dynamic" keyword – close but not perfect

 

The dynamic keyword is the next best thing to use native types.

 

What does the compiler do?

 

C# Compiler engineers are working with the Dynamic Language Runtime Team (DLR). You just don't know until runtime what the code is intending to do. C# code gets statically wrapped and passed to the DLR. This is not reflection.

 

The dynamic type is a real type

 

It ends up as an object and will invoke the DLR, using a runtime binder. Static fields are emitted, which are call sites. Lazy loaded the first time, but on subsequent calls, there is no need to re-jit the executable code.

 

The DLR is an assembly that sits there in system.core. It isn't just another virtual machine, depending on your definitions. There is no magic IL. The DLR provides services similar to a virtual machine. The DLR machinery is statically compiled into an assembly.

 

The call site has a target delegate, which takes the arguments that might be present with a function call. The point of the DLR is to cache your calls, so as to optimize repeated calls. The DLR will look at the parameters of a method call and try to build a specific delegate.

 

The big bonus

 

It is about the cache – cached IL

If you call a dynamic method 100's of times, the IL does not need to be re-emitted. The more you loop through a dynamic call the more closely you approach the performance of a static method call – due to the built in caching.

 

This is more powerful than your own reflection. The DLR is similar to a component of the compiler and has been given to you in the runtime (CLR).