In an async method I do a call like:
bool result = await SomeClassInstance.GetResultAsync();
GetResultAsync()
returns a Task<bool>
and thus can be await.
However, it may occur that SomeClassInstance
is null. In this case I want result
to be false
, i.e. have something like:
bool result = await SomeClassInstance?.GetResultAsync();
or
bool result = await SomeClassInstance.GetResultAsync() ?? false;
This however does not seem to be possible, since my first proposal throws a NullReferenceException
and the second will not compile since .GetResultAsync()
evaluates to a bool
and not bool?
and thus ??
can therefore not be applied.
Do I oversee something? Or is this just not possible in c#?
(I am aware of workarounds like: bool result = SomeClassInstance != null && await SomeClassInstance.GetResultAsync();
)
question from:
https://stackoverflow.com/questions/65644893/await-item-taskbool-such-that-item-can-be-null 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…