1

I have the following method from a library:

IRuleBuilderOptions<T1, T2> MustAsync<T1, T2>(this IRuleBuilder<T1, T2> ruleBuilder, Func<T2, CancellationToken, Task<bool>> predicate);

And I use it as follows:

.MustAsync((t2, token) => someAsyncMethodThatReturnsTaskBoolean());

But I am not able to negate the method as so:

.MustAsync((t2, token) => !someAsyncMethodThatReturnsTaskBoolean());

Because I get the error:

Operator "!" cannot be applied to operand of type Task<bool>

I cannot change the method because it is from an external library.

How can I solve this?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

4
async (t2, token) => !(await someAsyncMethodThatReturnsTaskBoolean())

This will complete the task and apply your ! to the result (ie. the boolean) rather than the task itself.

Alex F
  • 223
  • 2
  • 6
  • 2
    should remove the .Result answer....since that's just an awesome way to destroy asyncness – Steve Nov 09 '16 at 21:50
  • With your suggestion I get the error "The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier – Miguel Moura Nov 09 '16 at 21:51
  • And Result is just converting Task to bool which removes async behavior – Miguel Moura Nov 09 '16 at 21:52
  • Yes, the ! will always be applied after the function completes, so applying it here will require you not to have async behavior. I recommend adding the ! when you get the result of the function, though I can't peg exactly where that is without seeing more of your code. Basically, when you put that boolean to use, THEN apply the !. – Alex F Nov 09 '16 at 22:01
  • 2
    @MiguelMoura Use `.MustAsync( async (t2, token) => !(await someAsyncMethodThatReturnsTaskBoolean()));` – Kyle Nov 09 '16 at 22:21