org.sonar.plugins.csharp.S1751.html Maven / Gradle / Ivy
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
- Microsoft Learn - Iteration
statements -
for
, foreach
, do
, and while
- Microsoft Learn - Jump statements -
break
, continue
, return
, and goto
- Microsoft Learn - The
throw
statement
© 2015 - 2024 Weber Informatics LLC | Privacy Policy