ATBG: Why do enumerators avoid a bounds check?

I am back from a week in which I visited England, Holland, Belgium, France and Hungary; this is by far the most countries I’ve been to in so little time. It was great to meet so many customers; more on bicycling around Budapest in a future episode. For today though, I’ve posted on the Coverity Development Testing Blog’s continuing series Ask The Bug Guys a follow up to the previous episode. I’ll discuss why the struct-based list enumerator does not do bounds checking in its implementation of the Current property. Check it out! Thanks to reader Xi Chen for the question.


As always, if you have questions about a bug you’ve found in a C, C++, C# or Java program that you think would make a good episode of ATBG, please send your question along with a small reproducer of the problem to TheBugGuys@Coverity.com. We cannot promise to answer every question or solve every problem, but we’ll take a selection of the best questions that we can answer and address them on the dev testing blog every couple of weeks.

3 thoughts on “ATBG: Why do enumerators avoid a bounds check?

  1. Pingback: Dew Drop – June 4, 2014 (#1790) | Morning Dew

  2. I did a test and got confused by the decision of .Net team, array enumerator Current does throw an exception when accessed before MoveNext or after MoveNext returns false, as does the “yield” implementation, the documentation says that, in such situations the value of Current is undefined, and no word about exceptions, I think returning the default(T) is a valid return for undefined value and better then throwing a non-documented exception in a property (didn’t you bloged about it?), so, why such different behaviours for those enumerators?

    • I would expect that in the early days of .NET, it was probably expected that enumerators should go through the effort of throwing exceptions when used improperly, even in ways that could not be *expected* to return meaningful data. People realized later that this simply made code bigger and slower while offering no real advantage, causing this expectation to be relaxed. Code which uses the non-generic `IEnumerator` might for awhile have been somewhat more likely to expect an exception when `Current` is used improperly, though nowadays I don’t think such exceptions are particularly expected for `Current` even in the non-generic case.

Leave a comment