Quantcast
Channel: Answers by "gfoot"
Viewing all articles
Browse latest Browse all 95

Answer by gfoot

$
0
0
You can use the underlying iterators without creating the unnecessary garbage - essentially, you write what you would have liked the compiler to generate for you. The basic pattern is: var enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { var element = enumerator.Current; // loop body goes here } It is more complex though if the enumerator type is disposable, as you need to dispose of it appropriately, even if exceptions occur in your loop body. There are more details [here][1]. I think in modern parlance you can handle the exceptions more tidily than the linked page does, like this: using (var enumerator = collection.GetEnumerator()) { while (enumerator.MoveNext()) { var element = enumerator.Current; // loop body goes here } } In practice though I would guess that any enumerator which requires disposal is going to create garbage anyway, and so you might as well just use the "foreach" in that case. [1]: http://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx

Viewing all articles
Browse latest Browse all 95

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>