foreach readonly

T

Tony Johansson

Hello!

Here I have a simple program that is changing the object that is refering by
the car reference. This works.
Now to my question foreach is readonly and I assume that this must mean that
I'm not allowed to change in this example the
reference car that is refering to the car object when I enumerate through
the collection.?

public static void Main()
{
Car[] vector = { new Car(), new Car(), new Car() };
foreach (Car car in vector)
{
car.Year *= 2;
}
}

class Car
{
int year = 1;

public int Year
{
get { return year; }
set { year = value; }
}
}

//Tony
 
J

Jeff Johnson

Here I have a simple program that is changing the object that is refering
by the car reference. This works.
Now to my question foreach is readonly and I assume that this must mean
that I'm not allowed to change in this example the
reference car that is refering to the car object when I enumerate through
the collection.?

public static void Main()
{
Car[] vector = { new Car(), new Car(), new Car() };
foreach (Car car in vector)
{
car.Year *= 2;
}
}

class Car
{
int year = 1;

public int Year
{
get { return year; }
set { year = value; }
}
}


You can alter the properties of the Car object all you want. Often that's
what you made the loop for in the first place. What you cannot do is change
the COLLECTION itself. In other words, you can't mess around with vector.
With an array this generally isn't a problem since there isn't much you can
do to them, but if the source collection had been, say, a List<>, you
wouldn't want to (or be able to) add or remove items from the list.
 
J

Jeff Johnson

Correct: the List<T> class treats any modification, including even trying
to assign a new value to an element of the list, as an error.

Note however that in any case, the collection isn't actually read-only.
You _can_ modify it. It's just that modifying the collection causes the
enumerator's MoveNext() method to throw an exception the next time it's
called.

If you have a List<int> and try to modify one of the ints, yes. But if you
have List<MyClass> and you change a property of that class (as opposed to
replacing that instance with another instance) during iteration there's no
problem, right?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top