karakav
asked on
.NET: Safety with foreach iterations
I heard that when iterating through a collection using foreach statement it is not wise to change the content of the collection. Does this mean that one cannot change properties of the collection entries. I mean that if, for instance, I have Employee objects in a collection, can I change some attribute of each Employee while looping. I know it is possible syntaxically and the compile won't say anything. Is it a good practice.
Changing property of elements is ok. What you cannot do is adding or removing collection elements
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
if you want to delete an object run the loop backwards.
The following will work fine:
The following will work fine:
for(int i=collection.Length-1; i >=0; i--)
{
if(i%2)=0
//delete the object
}
ASKER
Thanks.