Search code examples
c#linqlambdaexpression-trees

How to manually build Expression which will return always true?


I tried to create Expression, but failed.

I want to build something like Expression<Func<typeof(type), bool>> expression = _ => true;

My attempt:

private static Expression GetTrueExpression(Type type)
{
    LabelTarget returnTarget = Expression.Label(typeof(bool));
    ParameterExpression parameter = Expression.Parameter(type, "x");

    var resultExpression = 
      Expression.Return(returnTarget, Expression.Constant(true), typeof(bool));

    var delegateType = typeof(Func<,>).MakeGenericType(type, typeof(bool));

    return Expression.Lambda(delegateType, resultExpression, parameter); ;
}

Usage:

var predicate = Expression.Lambda(GetTrueExpression(typeof(bool))).Compile();

But I am getting the error: Cannot jump to undefined label ''


Solution

  • As simple as that:

    private static Expression GetTrueExpression(Type type)
    {
        return Expression.Lambda(Expression.Constant(true), Expression.Parameter(type, "_"));
    }