C# Working With ArrayList: What is the best Iterator choice?(coderpaws.blogspot.com)

submitted by CoderPawsCoderPaws(140) 1 year, 8 months ago

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."

1 comment |category: |Views: 346

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by sdormansdorman(1415) 1 year, 7 months ago 0

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.

Reply

information Login or create an account to comment on this story