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 "";
}
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.
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.
1) forEach method Also, forEach method doesn't return anything (undefined).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With