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:
Public Function Method(items As IEnumerable(Of Object)) As Object
For i As Integer = 0 To 9
Console.WriteLine(i)
Exit For ' Noncompliant: loop only executes once
Next
For Each item As Object In items
Return item ' Noncompliant: loop only executes once
Next
Return Nothing
End Function
Public Function Method(items As IEnumerable(Of Object)) As Object
For i As Integer = 0 To 9
Console.WriteLine(i)
Next
Dim item = items.FirstOrDefault()
If item IsNot Nothing Then
Return item
End If
Return Nothing
End Function
Exit Statement (Visual
Basic) Continue Statement
(Visual Basic) Return Statement (Visual
Basic) Throw Statement (Visual
Basic)