All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S4586.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

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





© 2015 - 2024 Weber Informatics LLC | Privacy Policy