Wednesday 26 November 2008

Dynamic Operators

One of the interesting proposed features mentioned in the C# 4.0 CTP documents is operator support on "dynamic". I've done a lot of looking at generic operators in the past, but this potentially allows for a new answer for operators with generics - something of the type:

        public static T Add<T>(T x, T y)
dynamic xDynamic = x, yDynamic = y;
return xDynamic + yDynamic;

Unfortunately, the support for operators on dynamic didn't make it into the current CTP bits, so we can't try this yet. But certainly one to watch in the next CTP.

However, looking at the complexity involved behind the scenes with dynamic, I suspect that this isn't going to be nearly as efficient as some of the things you can already do in .NET 3.5 by pre-compiling an Expression to a Func<T,T,T>, like here. A heavily-cut down version of this can be written as follows:

        static class Operator<T>
private static readonly Func<T, T, T> add;
public static T Add(T x, T y) { return add(x, y); }
static Operator()
var x = Expression.Parameter(typeof(T), "x");
var y = Expression.Parameter(typeof(T), "y");
add = Expression.Lambda<Func<T, T, T>>(
Expression.Add(x, y), x, y).Compile();

In terms of expression-trees, that is about as simple as they get - but very useful for providing things like operator support. Obviously the code in MiscUtil allows a lot more flexibility ;-p

But! In many cases you aren't going to be doing heavy number crunching... so maybe an occasional dynamic call is acceptable if it reduces some external code. Once the CTP supports it, I will be sure to run a performance test to see where the split lies.