Search code examples
c#linqexpression-trees

How to create an Expression that invokes (or is combined with) another Expression using a closure object as argument?


I will first show a fully working equivalent that does not use expression-trees:

public class ClassUsingFuncs
{
    public SomeClass SomeProperty { get; set; }

    public void DoSomethingUsingFuncWithoutArgument(Func<bool> funcWithoutArgument)
    {
    }

    public void DoSomethingUsingFuncWithArgument(Func<SomeClass, bool> funcWithArgument)
    {
        Func<bool> funcWithoutArgument = () => funcWithArgument(SomeProperty);
        DoSomethingUsingFuncWithoutArgument(funcWithoutArgument);
    }
}

How do I achieve the equivalent for this when using expression-trees? It's no problem if I will need LINQKit or some other library to achieve this.

public class ClassUsingExpressionTrees
{
    public SomeClass SomeProperty { get; set; }

    public void DoSomethingUsingExpressionWithoutArgument(Expression<Func<bool>> expressionWithoutArgument)
    {
    }

    public void DoSomethingUsingExpressionWithArgument(Expression<Func<SomeClass, bool>> expressionWithArgument)
    {
        Expression<Func<bool>> expressionWithoutArgument = ?
        DoSomethingUsingExpressionWithoutArgument(expressionWithoutArgument);
    }
}

Solution

  • public void DoSomethingUsingExpressionWithArgument(Expression<Func<SomeClass, bool>> expressionWithArgument)
    {
        var thisExpr = Expression.Constant(this);
        var pExpr = Expression.Property(thisExpr, "SomeProperty");
        var invokeExpr = Expression.Invoke(expressionWithArgument, pExpr);
        Expression<Func<bool>> expressionWithoutArgument = Expression.Lambda<Func<bool>>(invokeExpr);
        DoSomethingUsingExpressionWithoutArgument(expressionWithoutArgument);
    }