Dynamic in C# - why what's new is more than what's old

Tags: duck typing, what's old is new, dynamic dispatch, C#, .net, dynamic

A quick look at the new dynamic keyword in c# 4.0, it's predecessors, and why it's not the same this time.

Anders Hejlsberg's first major language of TurboPascal/Delphi acquired many features in its long life. And so it became a large language with many ways of doing things. C# is also walking that line between adding features and adding complexity, and doing a reasonable job of it.

The .Net 4.0 dynamic keyword adds complexity and features, and it's a path that has been trodden before.
Delphi had a similar feature with the "Variant" data type (the dynamic keyword was already in use for one flavour of Delphi virtual method). It was used for similar reasons - iterop with external code where the type couldn't be discovered ahead of time. In Delphi's case it was VB, COM and OLE automation that had to be connected to. Using a variant, type, property and method names would be resolved at runtime. Other than that the addition of "variant" to the language didn't change a lot. You didn't want to do any serious work in variants – you lost the speed and type checking that was the point of working in a statically and strongly typed language, and didn't gain much in return.

In .Net a decade later it's other systems to be connected to: typically JavaScript, Python, Ruby or data in Json or XML form. So other than what you connect to, is dynamic in .Net just the same as variant was?

I think it isn't. There is more, there are new things that are interesting and that were not present then. They come from coding the dynamic objects in .Net languages. There are several classes that can be used as base classes for your own dynamic object schemes or used as is.

The first new capability is that you can intercept missing methods. Ruby and Python have already proved the uses of this technique.

Based on this, you can attach methods to dynamic objects on the fly. This is done a lot in Javascript. This can now be done in C# 4 with code like this:

dynamic testObject = new ExpandoObject();
testObject.SayHello = (Action)(() => { Console.WriteLine("Hello, dynamic."); });
testObject.SayHello();

See links to the ExpandoObject definition and discussion. The second line has a lot of noise on it, it would be easier if it could be written something like:

testObject.SayHello = () => { Console.WriteLine("Hello, dynamic."); };

or even

testObject.SayHello = { Console.WriteLine("Hello, dynamic.") };

But this does not have enough type info on it to compile.

You don't have a JavaScript-style prototype inheritance out of the box, but you could build something like it if you tried.

Dynamic in .Net is not just about interop, despite the similarity with similar features in the 1990s in Delphi.

Further reading: The posiblities of Dynamic in C#

 

Add a Comment