cnom
cnom

Reputation: 3241

Iterating a list of objects with foreach

I came across this statement:

"When using foreach on a list of objects, the iterated object instance is not editable, but the object properties are editable"

Could someone demonstrate the above with a simple example, please?

Let me re-phrase (as I found the statement in two versions), maybe this statement is more clear:

"When using foreach on a list of elements, the iteration variable that provides the element is readonly, but the element properties are editable"

Upvotes: 8

Views: 47368

Answers (5)

lolex
lolex

Reputation: 65

foreach var car in cars 
{
    //you can edit car.color here
    //you cannot edit car
}

Upvotes: 0

LordWilmore
LordWilmore

Reputation: 2912

Not sure you need an example for this. You will step over each object in the collection, and you can do what you like to each of those objects, but you can't make changes to the collection itself, e.g. Insert, Remove, Clear, etc. Attempting such will throw an exception.

Upvotes: 0

Neil
Neil

Reputation: 11889

What is means is that the items in the list can't change whilst iterating, but the contents of the items may.

this will alter the collection and prevent the foreach completing:

foreach(var item in collection)
{
   collection.Remove(item);
}

This will change an item in the list and not prevent the foreach completing:

foreach(var item in collection)
{
    item.name = "Neil";
}

Upvotes: 1

user6522773
user6522773

Reputation:

foreach(var foo in foos)
{
  foo = null; // WRONG, foo is not editable
  foo.name = "John";  // RIGHT, foo properties are editable
}

Upvotes: 12

BugFinder
BugFinder

Reputation: 17858

Yes

Foreach (n in list) if (n.something==true) list.Remove(n);

this will fail

you cannot remove an item in list, unlike say a for loop

Upvotes: 0

Related Questions