Error passing both a dynamic object and an Action to a function

I am trying to pass a dynamic object and an Action into a function. (below is a simple test) But, I am getting the following compile time error:

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.

One or the other is ok... but not both... any help?

    void Test()
    {
        dynamic obj = new System.Dynamic.ExpandoObject();
        obj.A = 1;
        obj.B = 2;
        Calc(obj, (result) =>
        {
            Console.Write("Result: " + result);
        });    
    }

    void Calc(dynamic obj, Action<int> onComplete)
    {
        onComplete((int)obj.A + (int)obj.B);
    }
Jon Skeet
people
quotationmark

Sure - do exactly as the compiler says - cast the lambda expression to a concrete type:

Calc(obj, (Action<int>)(result => Console.Write("Result: " + result)));

The reason you have to do this is that a lambda expression doesn't have a type - the compiler has to know what delegate (or expression tree) type you're trying to convert it to. It can't do that if the method you'll be calling won't be chosen until execution time, which is the case when another argument is dynamic.

people

See more on this question at Stackoverflow