== Why is this an issue?

A https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements[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 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements[jump statement] or a https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/exception-handling-statements#the-throw-statement[throw statement], is misplaced inside the loop block.

This rule raises when the following statements are misplaced:

* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements#the-break-statement[`break`]
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements#the-continue-statement[`continue`]
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements#the-return-statement[`return`]
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/exception-handling-statements#the-throw-statement[`throw`]

== How to fix it

=== Code examples

==== Noncompliant code example

[source,csharp,diff-id=1,diff-type=noncompliant]
----
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

[source,csharp,diff-id=1,diff-type=compliant]
----
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 - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements[Iteration statements - `for`, `foreach`, `do`, and `while`]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements[Jump statements - `break`, `continue`, `return`, and `goto`]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/exception-handling-statements#the-throw-statement[The `throw` statement]

include::../rspecator-dotnet.adoc[]
