Why is this an issue?
Returning null from a non-async Task/Task<TResult> method will cause a
NullReferenceException at runtime if the method is awaited. This problem can be avoided by returning Task.CompletedTask or Task.FromResult<TResult>(null)
respectively.
public Task DoFooAsync()
{
return null; // Noncompliant: Causes a NullReferenceException if awaited.
}
public async Task Main()
{
await DoFooAsync(); // NullReferenceException
}
How to fix it
Instead of null Task.CompletedTask or Task.FromResult<TResult>(null)
should be returned.
Code examples
A Task returning method can be fixed like so:
Noncompliant code example
public Task DoFooAsync()
{
return null; // Noncompliant: Causes a NullReferenceException if awaited.
}
Compliant solution
public Task DoFooAsync()
{
return Task.CompletedTask; // Compliant: Method can be awaited.
}
A Task<TResult> returning method can be fixed like so:
Noncompliant code example
public Task<object> GetFooAsync()
{
return null; // Noncompliant: Causes a NullReferenceException if awaited.
}
Compliant solution
public Task<object> GetFooAsync()
{
return Task.FromResult<object>(null); // Compliant: Method can be awaited.
}
Resources
Documentation
- Microsoft Learn -
Task.CompletedTaskProperty - Microsoft Learn -
Task.FromResult<TResult>(TResult)Method
Articles & blog posts
- StackOverflow - Answer by Stephen Cleary for Is it better to return an empty task or null?
- StackOverflow - Answer by Stephen Cleary for Best way to handle null task inside async method?
- C# Language Design - Proposal Champion "Null-conditional await"