Link to home
Start Free TrialLog in
Avatar of karakav
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.
Avatar of philipjonathan
philipjonathan
Flag of New Zealand image

Changing property of elements is ok. What you cannot do is adding or removing collection elements
ASKER CERTIFIED SOLUTION
Avatar of Toms Edison
Toms Edison
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of openshac
openshac

if you want to delete an object run the loop backwards.

The following will work fine:
for(int i=collection.Length-1; i >=0; i--)
{
 if(i%2)=0
 //delete the object
}

Open in new window

Avatar of karakav

ASKER

Thanks.