Tuesday, 20 April 2010

Using dynamic to simplify reflection (and: generic specialization)

As I’ve noted in the past; reflection and generics don’t mix very well. The story isn’t quite as bad in .NET 4 though; here’s an example of something that is just painful to call (for the correct T known only at runtime) in C# 3.0:

And remember – we’re talking about the scenario where T is onlyknown at runtime:

Previously we needed to use lots of MakeGenericMethod (or MakeGenericType) – things like:

You can see how that might quickly become boring. But in .NET 4 / C# 4.0 we can exploit “dynamic” to do all the heavy lifting and cache a delegate per scenario for us:

Much better!

Another possible use of this is generic type specialization:

Now this version is called for `int` arguments, otherwise the generic version is called – just as would have been the case from static C#. Magic!