7

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 ''

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Mickey P
  • 183
  • 1
  • 10

2 Answers2

18

As simple as that:

private static Expression GetTrueExpression(Type type)
{
    return Expression.Lambda(Expression.Constant(true), Expression.Parameter(type, "_"));
}
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
-1

I had to face the same issue, and got this code. It seems to be clean and simple.

Expression.IsTrue(Expression.Constant(true))
Ygalbel
  • 5,214
  • 1
  • 24
  • 32
  • I have no idea. I think it's because my answer don't take a parameter. – Ygalbel Apr 30 '20 at 20:11
  • 2
    I guess because OP is looking for a "callable generic function Expression" and this is just a "True" expression. Ivan Stoev's answer is clever. Creates an expression that represents a lambda, when you call the lambda expression with any type of parameter (just one) always returns true. – dani herrera Apr 30 '20 at 20:17