views:

45

answers:

2

Hi,

If do:

foreach(var a in col) {
     a.X = 1;
}

Will my iterator over the collection become invalid?

Thanks

+2  A: 

No. You can access the members of the items in the collection. Your code is valid.

What you can't do is modifying the collection itself (by removing or adding items to it) while iterating.

Yann Schwartz
+2  A: 

It shouldn't cause a problem. Only if you try to modify the contents of col by doing col.Remove or col.Add would I imagine there would be a problem.

Pwninstein
Thanks everyone:) I was in doubt because this sentence in doc:"If changes are made to the collection, such as adding, *modifying*, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined."
Vando
I guess in this context 'modifying' refers to replacing an element of the collection.
Daniel Fortunov