Miguel Moura Miguel Moura - 1 year ago 70
C# Question

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

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?

Answer Source
async (t2, token) => !(await someAsyncMethodThatReturnsTaskBoolean())

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