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 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
Compliant solution
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
Resources
Documentation
- Microsoft Learn - Loop Structures (Visual Basic)
- Microsoft Learn -
ExitStatement (Visual Basic) - Microsoft Learn -
ContinueStatement (Visual Basic) - Microsoft Learn -
ReturnStatement (Visual Basic) - Microsoft Learn -
ThrowStatement (Visual Basic) - Microsoft Learn - Throw Statement (Visual Basic)