Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a bug with nested invoke of LambdaExpression?

Tags:

c#

lambda

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;
        }
    }
}
like image 453
kitafan Avatar asked Jul 05 '10 08:07

kitafan


1 Answers

Since nobody seems to be posting this:

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

like image 198
zebediah49 Avatar answered Nov 17 '22 19:11

zebediah49