Is it possible to check that a simple expression will always return true?

Svi*_*ish 2 c# lambda unit-testing expression-trees

And I mean this in the easiest way. Say you have a function with the following signature:

public static Expression<Func<T, bool>> CreateExpression<T>(string value)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

Usually it will create a more complex expression of some sort, but if the value is null the method should return a constant, always true expression. In other words:

public static Expression<Func<T, bool>> CreateExpression<T>(string value)
{
    if(value == null)
        return x => true;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

Is this something I can create a unit test for? That when I send in null as the value, I do get back a constant true expression?

Mar*_*ell 6

这将是很容易的,以测试究竟该表达式(身体将是一个ConstantExpression具有价值true).但在一般情况下呢?不 - 太复杂了.

static bool IsConstantTrue(LambdaExpression lambda)
{
    return lambda.Body.NodeType == ExpressionType.Constant
        && true.Equals(((ConstantExpression)lambda.Body).Value);
}
Run Code Online (Sandbox Code Playgroud)

Expression<Func<SomeType, bool>> exp = x => true; // or some method that 
                                                  // returns a lambda expression
Assert.IsTrue(IsConstantTrue(exp));
Run Code Online (Sandbox Code Playgroud)