1

I have a small card game I'm making and the foreach loop throws an error on the last iteration in the collection. I assumed it was to do with the memory addressing so added the handTemp list to be iterated through instead. Still throws the same error though, can anybody help? thanks.

List<Card> handTemp = new List<Card>();
handTemp = players[0].hand;

foreach (Card c in handTemp)
{
   if (c.strName == crd.strName)
   {
       players[0].hand.Remove(c);
       pile.Add(c);
   }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
luigivampa
  • 377
  • 7
  • 22

2 Answers2

2

Your idea with the handTemp variable is correct, but you have an error in your implementation:

List<Card> handTemp = new List<Card>();
handTemp = players[0].hand;

This basicaly says 'create a new variable handTemp, assign to it a new list and then completely discard that list, instead pointing handTemp to players[0].hand'. What you probably wanted to do is:

List<Card> handTemp = new List<Card>(players[0].hand);

Alternatively, as Henk commented below, if you're in the wonderful world of .NET 3.5+, you might use the LINQ method:

var handTemp = players[0].hand.ToList();
decPL
  • 5,384
  • 1
  • 26
  • 36
  • That is not an error, and also not an answer to question. – Maarten Apr 02 '14 at 11:04
  • 1
    @Maarten Not sure I follow: this fix would make the presented code work without error. One could comment about performance vs a `for` loop, but such comments are hard to make in vacuum (and given those objects represent players' hands in a small card game I don't expect the collections to be significantly large). – decPL Apr 02 '14 at 11:10
  • 1
    @decPl I've misread a thing in your answer, my apologies. You are correct. – Maarten Apr 02 '14 at 11:15
  • Maarten, decPL thanks for the input. I think I've got it now. :) – luigivampa Apr 04 '14 at 13:00
0

If i have understand your problem clearly here players[0].hand and handTemp are reference type.

so in foreach while you removing item from players[0].hand it refers that you are also removing item from handTemp.

Note: a collection cannot be modified at the same time you are iterating through it.

to resolve this you can replace, handTemp = players[0].hand; with handTemp = players[0].hand.ToList();

.ToList() will create a new List() and will not affect handTemp to be modified.

Hope this help. correct me if i am wrong.

Rezoan
  • 1,745
  • 22
  • 51