Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
VB
For i = 0 To ModifiableSetting.Count - 1
    Dim key = ModifiableSetting.Keys(i)
    ModifiableSetting(key) = True
Next

The above code works. The code below gets me the exception.
They should cause the same results so why the exception?
VB
For Each key In ModifiableSetting.Keys
    ModifiableSetting(key) = False
Next



Just Puzzled

Leon
Posted

1 solution

Because the For Each loop is altering the target of the loop - which is a no-no!

The for loop modifies an index value each time round, so it's fine to alter the content of the Keys collection - or even to delete them. That doesn't affect anything, because the Count of the number of objects is recalculated each time round the loop, so even adding or removing items doesn't affect the "current" location.

But a For Each doesn't "complete" the collection, it uses an iterator which which "travels" through the collection each time round the loop. As such, when you try to modify the collection the iterator detects that and throws an exception.
 
Share this answer
 
Comments
MJ2014 26-Jun-15 13:26pm    
here it will uses an enumeration method.it will execute one iteration before data get modify.Once you have modified an index you will get an error in executing another . Because once Collection is modified ,the enumeration operation may not execute.
rogsonl 26-Jun-15 17:39pm    
So it has no way to realize that no new item has been added or deleted? That is the only thing an iterator should be interested in. After all we often modify information as we scan through it.

It is intuitive that you can't add/substract item, not that you can't modify it since there are no id fields involved.
Leon

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900