Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

c# - await item.Task<bool>() such that item can be null

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are different ways you could do it, e.g.:

// #1
bool result = await (SomeClassInstance?.GetResultAsync() ?? Task.FromResult(false));
// #2
bool result = SomeClassInstance != null : await SomeClassInstance.GetResultAsync() : false;

If you're trying to make calling GetResultAsync more compact and avoid null-checking, then either you should make sure that SomeClassInstance is never null or you could wrap the call in another method like so:

class SomeClass
{
    private SomeClassInstance { get; set; }

    public async Task<bool> GetNullSafeResult()
    {
        return await (SomeClassInstance?.GetResultAsync() ?? Task.FromResult(false));
    }
}

And then always call GetNullSafeResult instead of using SomeClassInstance directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...