Skip to content

Non Async Task Null

Methods that return null in non-async "Task/Task" should be avoided.

What does this mean ?

"Task/Task" methods that are not async should not return null. A NullReferenceException will be thrown at runtime if a non-async Task/Task function returns null.

What can happen ?

At execution, it will throw a NullReferenceException.

Recommendation

Returning Task will solve this problem. Instead, use FromResult(null).

Sample Code

Vulnerable :

public Task<object> GetFooAsync()
{
    return null; // Noncompliant
}

Non Vulnerable :

public Task<object> GetFooAsync()
{
    return Task.FromResult<object>(null);
}

References