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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

A loop statement with at most one iteration is equivalent to an if statement; the following block is executed only once.

If the initial intention was to conditionally execute the block only once, an if statement should be used instead. If that was not the initial intention, the block of the loop should be fixed so the block is executed multiple times.

A loop statement with at most one iteration can happen when a statement unconditionally transfers control, such as a jump statement or a throw statement, is misplaced inside the loop block.

This rule raises when the following statements are misplaced:

How to fix it

Code examples

Noncompliant code example

public object Method(IEnumerable<object> items)
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
        break; // Noncompliant: loop only executes once
    }

    foreach (object item in items)
    {
        return item; // Noncompliant: loop only executes once
    }
    return null;
}

Compliant solution

public object Method(IEnumerable<object> items)
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
    }

    var item = items.FirstOrDefault();
    if (item != null)
    {
        return item;
    }
    return null;
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy