How to simple and safe call a nullable delegate with await

Viewed 493

I have func<Task> delegates in my project which can be null. Is there any way to make the call of such a delegate simpler as displayed below?

public async Task Test()
{
    Func<Task> funcWithTask = null;

    await (funcWithTask != null ? funcWithTask.Invoke() : Task.CompletedTask);
}
1 Answers

Is there any way to make the call of such a delegate simpler as displayed below?

There are alternatives:

if (funcWithTask != null) await funcWithTask();

Or:

await (funcWithTask?.Invoke() ?? Task.CompletedTask);

The second uses the null-conditional operator ?., which only calls Invoke() when funcWithTask is not null, and the null-coalescing operator ?? which returns the right-hand operand when the left hand operand is null (Task.CompletedTask in this case).

Related