SirBirne
SirBirne

Reputation: 297

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.

Upvotes: 4

Views: 605

Answers (2)

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

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!");
    }
}

Upvotes: 2

christophano
christophano

Reputation: 935

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()));
    }
}

Upvotes: 5

Related Questions