tags:

views:

373

answers:

3

I tried to compile and calculate LambdaExpression like:

Plus(10, Plus(1,2))

But result is 4, not 13.

Code:

using System;
using System.Linq.Expressions;

namespace CheckLambdaExpressionBug
{
    class Program
    {
        static void Main(string[] _args)
        {
            ParameterExpression p1 = Expression.Parameter(typeof (int), "p1");
            ParameterExpression p2 = Expression.Parameter(typeof (int), "p2");
            LambdaExpression lambda = Expression.Lambda(Expression.Call(typeof(Program).GetMethod("Plus"), p1, p2), p1, p2);

            InvocationExpression exp1 = Expression.Invoke(
                lambda,
                Expression.Constant(1),
                Expression.Constant(2)
                );

            InvocationExpression exp2 = Expression.Invoke(
                lambda,
                Expression.Constant(10),
                exp1
                );

            var func = (Func<int>) Expression.Lambda(exp2).Compile();

            int v = func();
            Console.Out.WriteLine("Result = {0}", v);
        }

        public static int Plus(int a, int b)
        {
            return a + b;
        }
    }
}
A: 

whereas this seems to produce 13 in 3.5 too:

     var plus = new Func<int, int, int>((a, b) => a + b);
     var func = new Func<int>(() => plus(10, plus(1, 2)));
     var res = func();
     Console.WriteLine(res);
santa
You make too audacious supposition for the steps to reproduce it. Dont't stop, and try: int res = 10 + (1 + 2); You be amazed, it also return 13...In question I gave a concrete example to reproduce a problem. There is no sense to analyze other situations.
kitafan
you might be right on that one :=)
santa
A: 

maybe i needs to assign the result to a local var try this

var plus = new Func((a, b) => a + b); var puls_1 = plus(1, 2); var func = new Func(() => plus(10, plus_1)); var res = func(); Console.WriteLine(res);

chutzpah
+1  A: 

Since nobody seems to be posting this:

It looks to be a bug in .NET 3.5, and is fixed in .NET 4.

zebediah49