1

If do:

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

Will my iterator over the collection become invalid?

Thanks

Mark Carpenter
  • 17,445
  • 22
  • 96
  • 149
Vando
  • 179
  • 3
  • 9

2 Answers2

2

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
  • 5,954
  • 24
  • 27
2

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.

Mark Carpenter
  • 17,445
  • 22
  • 96
  • 149
  • 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 Nov 29 '09 at 17:32
  • I guess in this context 'modifying' refers to replacing an element of the collection. – Daniel Fortunov Nov 29 '09 at 18:01