Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any side effects of returning from inside a foreach statement?

Tags:

c#

foreach

Similar to my question about returning from inside a using statement (whose answer was generally "yes, it's ok") I'm wondering if returning from inside a foreach statement is similarly devoid of side-effects and considered accepted practice, or when I do this am I leaving a pointer hanging in the middle an enumeration somewhere internally, etc.

Here's an example:

public string GetCurrentTransaction(string idText)
{
    foreach (var transaction in transactions)
    {
        if (idText.IsEquivalentTo(transaction.IdText))
        {
            return transaction.Content;
        }
    }
    return "";
}
like image 251
Edward Tanguay Avatar asked Mar 04 '10 12:03

Edward Tanguay


People also ask

What happens if you return in a forEach?

You can't make JavaScript's forEach() function return a custom value. Using return in a forEach() is equivalent to a continue in a conventional loop.

Can you return out of a forEach?

You can't exit a forEach Loop, So Use every() Instead Once it's started, it will run until it reaches the last item in the array. So if you insert a break statement, it will return a SyntaxError : let numbers = [2, 4, 5, 8, 12] let odd = 5; numbers.

Does forEach return anything in JavaScript?

1) forEach method Also, forEach method doesn't return anything (undefined).

How do forEach loops work?

How foreach loop works? The in keyword used along with foreach loop is used to iterate over the iterable-item . The in keyword selects an item from the iterable-item on each iteration and store it in the variable element . On first iteration, the first item of iterable-item is stored in element.


3 Answers

Nope, dont see any issue with that.

From foreach, in (C# Reference)

A foreach loop can also be exited by the goto, return, or throwstatements.

like image 87
Adriaan Stander Avatar answered Sep 27 '22 16:09

Adriaan Stander


As long as nothing there implements IDisposable (or you have a using block around it), then that should be fine.

As far as I know, it's a fairly common and accepted practice and, as Astander mentions in his post, the documentation for foreach condones it as a legitimate practice.

like image 37
Justin Niessner Avatar answered Sep 27 '22 17:09

Justin Niessner


other than it being a small code smell to return from multiple points in methods (adds to the methods cyclomatic complexity) there is no technical reason to worry about.

like image 41
AndreasKnudsen Avatar answered Sep 27 '22 15:09

AndreasKnudsen