WHen you use a
foreach
loop, you set up and use something called an
enumerator
which returns each element in sequence as you go round the loop. If you change the object the
enumerator
is working on, it can't be sure which element to work on next, and so you get an error.
Effectively, the
foreach
loop sets up a for loop:
int count = deck.Count;
for (int i = 0; i < count; i++)
{
Card c = deck[i];
Console.WriteLine(c);
}
If you start removing cards inside the loop:
int count = deck.Count;
for (int i = 0; i < count; i++)
{
Card c = deck[i];
if (c.IsSpade)
{
deck.Remove(c);
}
Console.WriteLine(c);
}
Then it will cause two problems:
1) It will not print the card after the spade.
2) it will run off the end of the deck because the loop doesn't "know" that
i
shouldn't go that high anymore.
(
foreach
doesn't do it like that - it's rather more complicated internally - but the principle is the same)
You can't change the collection inside a
foreach
, or change the value of the
foreach
variable inside the loop.
Try this instead:
while(objStack.Count > 0)
{
Console.WriteLine(" {0}", objStack.Pop());
}
Or possibly:
foreach (Object i in objStack)
{
Console.WriteLine(" {0}", i);
}