Tuesday July 26th

Monday July 25th

C# Working With ArrayList: What is the best Iterator choice?

When you first look at which statement to use to iterate through an ArrayList collection, the foreach statement stands out. It's syntax is concise and readable as well as no extra lines of code are needed to extract the element you want to work with. But...[pause for effect]...if the collection is changed (e.g. adding, modifying, or deleting elements and even copying to it), you'll get a runtime error that the "Collection was modified."


This seems like common sense. If you are iterating over a collection (using any kind of a loop, but especially a foreach or a for) and you modify the underlying collection you are iterating things are going to go wrong.

A foreach loop essentially expects the collection to be immutable for the duration of the iteration. A for loop can change the value of an element in the collection as long as it doesn't add or remove an element from that same collection. In both cases, adding or removing an element from the collection means that the iterator code is now out of balance with the actual number of elements in the collection, so the iterator no longer knows what "MoveNext" would actually mean - hence the runtime exception.

Commenting on Stories is limited for now and will open up to those recommended by the community. Learn how
Loading DotNetKicks...
brought to you by the Kicks Network