Tag Archives: dynamic language

C# 4.0 and Dynamic Programming

In Microsoft PDC2008, Anders Hejlsberg — C# lead designer and Microsoft Technical Fellow — introduces the future of C#, dubbed C# 4.0. You can watch his recorded presentation at Channel 9. The following is a brief summary on dynamic programming, one of C# 4.0 new features.

C# Evolution

  • C# 1.0: Managed Code
  • C# 2.0: Generics
  • C# 3.0: Language Integrated Query
  • C# 4.0: Dynamic Programming

Nowadays, codes can reside in any kind of form, i.e., .NET objects, JavaScript, Python, Ruby, COM. In order to use the codes written in different form, currently we have some different approaches.

For example, to call a .NET object, we will write the following:

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

Now we try to call a .NET object too, but we don’t know which class exactly having the code:

object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 });
int sum = Convert.ToInt32(res);

While this is for calling a JavaScript object:

ScriptObject calc = GetCalculator();
object res = calc.Invoke("Add", 10, 20);
int sum = Convert.ToInt32(res);

Observe that there are different procedures to call different objects. With C# 4.0 dynamic keyword, we can use this instead of all those above:

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

The compiler will not check whether there is an “Add” method in the “calc” object. Instead, the DLR will bind the method call to the responsible object on runtime as shown in the following picture:

Dynamic Language Runtime

Anders stated that he did not have any intention to ask all developers to rewrite all their codes to be dynamic. In fact, he is a strong believer of static language strong features: statement completion, refactoring, compilation type check, and performance. But he also embraces the flexibility and productivity of dynamic languages such as Python and Ruby. And there are an increasing numbers of things that your application needs to talk to, that is not statically typed. You may need to talk to a JavaScript code, or maybe a Python or Ruby codes. The question is, should we make it painful to talk to them or make it easier?

For Anders, he wants the later. As LINQ intends to provide a unified way to access all kind of data source, dynamic in C# intends to provide a unified way to talk to all kind of codes, be it statically or dynamically typed.