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
.
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()));
}
}
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!");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With