Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write own assert Function with expressions

I would like to create my own Assert method similar to the code below, but it is not working.

// 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? The error is: 'Error 1 Cannot convert lambda to an expression tree whose type argument 'bool' is not a delegate type'.

First I had Expression<Func<bool>> expression and expression.Compile()() but this always crashed with TargetInvocationException.

like image 787
SirBirne Avatar asked Mar 17 '23 19:03

SirBirne


2 Answers

Expression<bool> is invalid as T must be a delegate type. Expression<Func<bool>> is valid, although I'm not sure why you prefer that over a simple Func<bool>. That's 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()));
    }
}
like image 53
christophano Avatar answered Mar 27 '23 10:03

christophano


This would work:

public static void Assert(Expression<Func<bool>> expression)
{
    if (!expression.Compile().Invoke())
    {
        throw new InvalidOperationException("Assert: " + expression.ToString() + " may not be false!");
    }
}
like image 41
Florian Schmidinger Avatar answered Mar 27 '23 10:03

Florian Schmidinger