How to simple and safe call a nullable delegate with await
Asked Answered
E

1

5

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);
}
Equate answered 20/5, 2021 at 15:19 Comment(4)
You can use null propagation: await funcWithTask?.Invoke()??Task.CompletedTask; The same you're doing but more compact.Kiyokokiyoshi
Or initialize the Func<Task> with a default of Func<Task> funcWithTask = () => Task.CompletedTask;Puparium
@DavidBrowne-Microsoft That is a good idea, but to be safe I have to prevented possible null assignments later on.Equate
In C# 8+ the compiler can help: learn.microsoft.com/en-us/dotnet/csharp/language-reference/…Puparium
B
11

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

Batiste answered 20/5, 2021 at 15:27 Comment(1)
if funcWithTask has return value, likes a string, you can try this alternatice: var taskResult = await (funcWithTask?.Invoke() ?? Task.FromResult(string.Empty));Octave

© 2022 - 2024 — McMap. All rights reserved.