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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Returning null or default instead of an actual collection forces the method callers to explicitly test for null, making the code more complex and less readable.

Moreover, in many cases, null or default is used as a synonym for empty.

Noncompliant code example

public Result[] GetResults()
{
    return null; // Noncompliant
}

public IEnumerable<Result> GetResults(bool condition)
{
    var results = GenerateResults();
    return condition
        ? results
        : null; // Noncompliant
}

public IEnumerable<Result> GetResults() => null; // Noncompliant

public IEnumerable<Result> Results
{
    get
    {
        return default(IEnumerable<Result>); // Noncompliant
    }
}

public IEnumerable<Result> Results => default; // Noncompliant

Compliant solution

public Result[] GetResults()
{
    return new Result[0];
}

public IEnumerable<Result> GetResults(bool condition)
{
    var results = GenerateResults();
    return condition
        ? results
        : Enumerable.Empty<Result>();
}

public IEnumerable<Result> GetResults() => Enumerable.Empty<Result>();

public IEnumerable<Result> Results
{
    get
    {
        return Enumerable.Empty<Result>();
    }
}

public IEnumerable<Result> Results => Enumerable.Empty<Result>();

Exceptions

Although string is a collection, the rule won’t report on it.





© 2015 - 2024 Weber Informatics LLC | Privacy Policy