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
}
Instead of null Task.CompletedTask or Task.FromResult<TResult>(null)
should be returned.
A Task returning method can be fixed like so:
public Task DoFooAsync()
{
return null; // Noncompliant: Causes a NullReferenceException if awaited.
}
public Task DoFooAsync()
{
return Task.CompletedTask; // Compliant: Method can be awaited.
}
A Task<TResult> returning method can be fixed like so:
public Task<object> GetFooAsync()
{
return null; // Noncompliant: Causes a NullReferenceException if awaited.
}
public Task<object> GetFooAsync()
{
return Task.FromResult<object>(null); // Compliant: Method can be awaited.
}
Task.CompletedTask Property Task.FromResult<TResult>(TResult)
Method