Dynamic Programming in C# 4.0 – An Overview

One of the most interesting additions to C# 4.0, I think, is the dynamic addition. Just thinking about this makes me excited. I will jump right into a little theory then some code.

The Theory of Dynamic

So what is this here dynamic thingy? dynamic in C# 4.0 refers to dynamic binding and dynamic binding is what happens at runtime and not at compile time. This involves binding a method, property, operator, member etc of an object at runtime. Yes I know this sounds like polymorphism or like the var keyword or even like using the ultimate base class in C# – object. First and foremost you have to let go or what you know and remember this important fact.

dynamic != var && dynamic != object

The keyword dynamic, casually speaking, tells the compiler that “Even though it cannot resolve the member statically, it should trust the programmer and don’t worry because it will/may be resolved at runtime.”

Code

Here is a sample on how you use the dynamic keyword:

dynamic dyn = “My first time”;
Console.WriteLine(dyn);

Now let’s look at some similarities and differences of var, object, and dynamic for a sec.

var v = 1; // here the compiler will figure out (at compile time) the type for v which will be int.
Console.WriteLine(v.GetType().ToString());
//v.Compute(); // causes a compiler error
object o = 1; // this is boxed from value type to an object with type being int32
Console.WriteLine(o.GetType().ToString());
//o.Compute(); //also gives a compiler error
dynamic d = 1; //type here is int32
Console.WriteLine(d.GetType().ToString());
d.Compute(); // does not give compile time error but will throw a runtime RuntimeBinderException

Continue reading

Advertisements