D
D
DancingOnWater2016-04-28 15:54:35
C++ / C#
DancingOnWater, 2016-04-28 15:54:35

What is wrong with Lambdaexpression created from BinaryExpression?

During the discussion of the topic of the expression tree in C#, a question arose that is best demonstrated by this code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

class Program
{
    static void Main()
    {
        List<int> corrections = new List<int>{1,2,3};
        Expression<Func<int, bool>> previousExpression = x=> x == corrections[0];

        Expression<Func<int, bool>> filterFunctor, comparison = x=> x == corrections[1] || x == corrections[0];
        Expression<Func<int, bool>> currentExpression = x => x == corrections[1];
        var result = Expression.OrElse(currentExpression.Body, previousExpression.Body);
        filterFunctor = Expression.Lambda<Func<int, bool>>(result, previousExpression.Parameters.Single() );
                
        Console.WriteLine( filterFunctor.Compile());
        Console.WriteLine( comparison.Compile() );

    }
}

comparison is easy to compile, but filterFunctor will throw an exception
[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidOperationException: variable 'x' of type 'System.Int32' referenced from scope '', but it is not defined

And I have absolutely no idea what it means, how it arose and how to fix it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2016-04-28
@DancingOnWater

'x' in previousExpression and 'x' in currentExpression are treated as different variables. You must explicitly specify that one of the lambdas, such as currentExpression, should be called with the same variable as the other. For example, try this:
And yes, you could clean up the code before asking a question, for 10 minutes I was just trying to understand what you are doing. Do you think this line is easy to read?
In addition to the fact that you do not take a lambda in brackets, you also declare two variables in one statement.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question