Create your own assert function with expressions

I would like to create my own method Assertsimilar to the code below, but it does not work.

// Method Usage
Argument.Assert(() => Measurements.Count > 0);

// Method Implementation
public static void Assert(Expression<bool> expression)
{
  bool value = expression.Compile();
  if(!value)
  {
    throw new InvalidOperationException("Assert: " + expression.ToString() + " may not be false!");
  }
}

What am I doing wrong here? Error: 'Error 1 Cannot convert lambda to an expression tree whose type argument 'bool' is not a delegate type'.

At first I had Expression<Func<bool>> expressionand expression.Compile()(), but it always fails with TargetInvocationException.

+4
source share
2 answers

Expression<bool>not valid since T must be a delegate type. Expression<Func<bool>>indeed, although I'm not sure why you prefer this over the simple Func<bool>. This is your call.

This should work

public static void Assert(Expression<Func<bool>> expression)
{
    if (!expression.Compile().Invoke())
    {
        throw new InvalidOperationException(String.Format("Assert: {0} may not be false!", expression.ToString()));
    }
}
+5
source

This will work:

public static void Assert(Expression<Func<bool>> expression)
{
    if (!expression.Compile().Invoke())
    {
        throw new InvalidOperationException("Assert: " + expression.ToString() + " may not be false!");
    }
}
+2
source

All Articles