C# 4: Real-World Example of Dynamic Types

There are lots of cases where you are already using dynamic typing and dynamic binding today. You just don’t realize it, because it is all hidden behind strings or System.Object, since until C# 4, the necessary support wasn’t there.

One example is COM interop: COM is actually a semi-dynamic object system. When you do COM interop, a lot of methods actually return a dynamic object, but because C# didn’t support them, they were returned as System.Object and you had to cast them yourself, possibly catching exceptions on the way.

Another example is interacting with dynamically typed (or even untyped) data, such as JSON, CSV, HTML, schemaless XML, schemaless web services, schemaless databases (which are, after all, the new hotness). Today, you use strings for those. An XML API would look like

var doc = new XmlDocument("/path/to/file.xml");
var baz = doc.GetElement("foo").GetElement("qux");

and so on. But how about:

dynamic doc = new XmlDocument("/path/to/file.xml");
var baz = doc.foo.qux;

Doesn’t that look nice?

A third example is reflection. Today, invocation of a method via reflection is done by passing a string to InvokeMember (or whatever the thing is called). Wouldn’t it be nicer to, you know, just invoke the damn thing?

Then, there is generation of dynamic data (basically the opposite of the second example). Here’s an example how to generate some dynamic XML:

dynamic doc = new XmlBuilder();
doc.articles(id=42, type="List", () => {
  article(() => {
    number(42);
    title("blahblubb");});});

This is not nearly as beautiful as the equivalent Ruby, but it is the best I could come up with at such short notice 🙂

And last but certainly not least, integration with a dynamically typed language. Whether that is JavaScript in a Silverlight application, a custom rules engine embedded in your business app or a DLR instance that you host in your CAD program/IDE/text editor.

Leave a Comment