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
Articles & blog posts