6

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
  • 165,109
  • 17
  • 150
  • 199
Mickey P
  • 153
  • 1
  • 9

2 Answers2

13

As simple as that:

private static Expression GetTrueExpression(Type type)
{
    return Expression.Lambda(Expression.Constant(true), Expression.Parameter(type, "_"));
}
Ivan Stoev
  • 179,274
  • 12
  • 254
  • 292
-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
  • 4,714
  • 21
  • 30
  • I have no idea. I think it's because my answer don't take a parameter. – Ygalbel Apr 30 '20 at 20:11
  • 1
    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