foreach issue

  • Thread starter Thread starter Jay
  • Start date Start date
J

Jay

When doing a foreach statement like the following why is the variable
read-only?

foreach (e in theArray)

What if I have an array of objects and I need to create a new instance of
the object. If the e is read-only then I have to use a for statement to
accomplish this.
 
Jay,

It is read-only just to prevent you for making mistakes.

*e* (in your example) is nothing more than a local variable. You may change
its value, but it won't affect the reference kept in the collection. Having
it read only let the compiler emit an error if this happens.

e.SomeProp = ...; at the other hand is correct code. However whether it is
going to chanage the object in the collection depends on what is the type of
the collection (array or non-typed collection) and what is the type of the
item (reference or value type).
 
i think a better way to put it is you can't change an element of your
enumerating through, if you have an array and you want to cycle through
it, you can make changes to the list your cycling through
 
There is a HUGE thread discussing the issue of non-mutable collections while
in a for-each statement, going on right now, on this group (called For vs
For Each). If you want a long discussion of the reasons, and complaints,
that come from making the collection read-only for the duration of the
for-each, please see that thread (many mvps weighing in).

--- N
 
i think a better way to put it is you can't change an element of your
enumerating through, if you have an array and you want to cycle through
it, you can make changes to the list your cycling through

Actually using *foreach* you cannot change the list per se, but you can
change the internal state of the items.
 
Back
Top