Search code examples
c#async-awaittask-parallel-librarynullreferenceexceptionfunc

How to simple and safe call a nullable delegate with await


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);
}

Solution

  • 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).