According to the "New features in CSharp 4.0" doc, dynamic operator dispatch is supported; is this implemented yet?
I was trying to compare to an existing mechanism for using operators with generics (via Expression), but it doesn't compile:
using System;
using System.Diagnostics;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
TestOperator<int>(10, 2);
TestDynamic<int>(10,2);
}
const int COUNT = 10000000;
static void TestOperator<T>(T seed, T inc)
{
T value = seed;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
value = OperatorCache<T>.Add(value, inc);
}
watch.Stop();
Console.WriteLine("Operator: {0} ({1})", watch.ElapsedMilliseconds, value);
}
static void TestDynamic<T>(T seed, T inc)
{
dynamic value = seed;
//dynamic tmp = inc;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
// Error 1 Operator '+' cannot be applied to operands of type '::dynamic' and 'T'
// (note I also tried with dynamic + dynamic, via "tmp")
value = value + inc; // tmp
}
watch.Stop();
Console.WriteLine("Dynamic: {0} ({1})", watch.ElapsedMilliseconds, value);
}
static class OperatorCache<T>
{
public static readonly Func<T, T, T> Add;
static OperatorCache()
{
var p1 = Expression.Parameter(typeof(T), "x");
var p2 = Expression.Parameter(typeof(T), "y");
var body = Expression.Add(p1, p2);
Add = Expression.Lambda<Func<T, T, T>>(body, p1, p2).Compile();
}
}
}