开发者

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

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 开发者_JS百科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 "";
}


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.


I don't know, but I'll make an educated guess: Since an enumerator typically doesn't implement IDisposable, it should be simply garbage-collected, because otherwise each use of that enumerator would leak unmanaged resources. Of course, technically, you can implement an enumerator that has side-effects on its own...

In other words, I never felt bad about returning from within a foreach block. I'd expect the language to handle things, just like with a using statement, where the language ensures that the object is disposed of (by implicitly calling Dispose in a finally block).


As far as i remember the enumeration stays on this position until the next foreach loop. This is however no problem as any following foreach returns the position back to the start of the enumeration. In short: It has no bad side effects unless you rely on IEnumerator.Current to have a specific value (which would be bad anyways).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜