C# dynamic and generics dispatch

I remember when C# 3 came out, I immediately started using pretty much all of the new features in it and I loved it. Imagine developing without var, automatic properties, lambdas, extension methods including those in .Linq namespace.

With C# 4 it’s been different. Even though it’s been several months since I started using Visual Studio 2010 and .NET 4, except for generic variance and occasional use of named arguments I hardly use any of the new features. Especially, I couldn’t find a good use case for the most hyped new feature – the dynamic keyword.

Until today, that is.

Short introduction to the problem

The application I’m working on right now, has forms (you wouldn’t expect that, would you?). Each of them collects some data in steps and based on answers from previous step, its own state etc, it decides whether or not it needs to collect more info or “does stuff”.

So the C# 3 version…

Each form (questionnaire) implements a common interface and various (multiple!) closed version of IHandleData<TData> interface for each type of data it collects from the user. The solution is very loosely generic, so the code that wires those things together does not know any details about the types it’s working with. All it knows is that it gets two objects – one of them is the data type, and the other implements generic IHandleData closed over the former type. It then has to somehow invoke the right one (of many) Handle method on the first object, passing the second one as the argument.

To handle this, we came up with code resembling the following (this code is simplified – the actual solution is a tad more elaborate):

var viewType = data.GetType();
var closedType = typeof(IHandleData<>).MakeGenericType(viewType);
var handle = closedType.GetMethod("Handle");
handle.Invoke(questionnaire, new[] { data });

There’s quite a lot of ceremony here, to work around the fact that at compile time we don’t have enough type information (and that type information are different from invocation to invocation) to satisfy the compiler.

Then again in C# 4…

In situations like this, involving generics and dynamic dispatch, you can leverage the new C# 4 capabilities, to make the code much neater and much more concise:

dynamic data = GetData();
dynamic questionaire = GetQuestionaire();

The additional benefit to vastly improved readability of the code is better performance. A useful thing to keep on the back of your head.


Mark Seemann says:

Very nice – I immediately went ahead and applied it in a similar scenario 🙂


Jan C Selke says:

Very neat, indeed. I was not sure whether an how to use dynamic, but this let’s me think about something…
Think I am going to use it soon 🙂