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.


There's one example on MSDN:

Many COM methods allow for variation in argument types and return type by designating the types as object. This has necessitated explicit casting of the values to coordinate with strongly typed variables in C#. If you compile by using the /link (C# Compiler Options) option, the introduction of the dynamic type enables you to treat the occurrences of object in COM signatures as if they were of type dynamic, and thereby to avoid much of the casting.

Another example is if you have to interop with dynamic languages.

Also there are some occasions where you want to make some code generic but you can't because even though the objects implement the same method, they don't share a suitable base class or interface that declares the methods you need. An example of this is trying to make something generic with ints and short. It's a bit of a hack, but dynamic allows you to call the same methods on these different types, allowing more code reuse.

Update: A bit of searching on here found this related post.


From Walter Almeida's Blog: a scenario of use of the dynamic keyword in C# to enhance object orientation:

http://blog.walteralmeida.com/2010/05/using-the-dynamic-keyword-in-c-to-improve-objectorientation.html


Scott Watermasysk wrote an article about using dynamics for dictionary key-property mapping on the MongoDB C# driver.

http://simpable.com/code/mongodb-dynamics/


I think others have given some great answers so far so I just want to add this example by David Hanson. Hist post shows the most practical application I've found so far for dynamic types in C# where he uses them to create proxy objects. In this example he creates a proxy which allows raising of exceptions on WPF binding errors. I'm not sure if this could also be achieved in the case of WPF bindings by using CustomTypeDescriptors and property descriptor concepts in general but regardless I think the use of the new C# 4.0 dynamic type is a great demonstration of its capabilities.

Raising binding exceptions in WPF & Silverlight with .net 4.0 Dynamics

One other use that I can think of for Dynamic types is to create proxies that similarly can be plugged in as a DataContext in WPF or in other places where a generic object type is expected and reflection methods are normally used to interrogate the type. In these cases especially when building tests a dynamic type can be used which would then allow property accessors to be called and logged accordingly by the proxy object in a dynamic fashion without having to hardcode properties within a test-only class.