0

This is a part of an static int method:

int answer = 0;
foreach(int getal in savedNumbers)
{
    Console.WriteLine(getal);
    answer = answer + getal;
    savedNumbers.Clear(); // after this line, I'm getting an error.
}
return answer;

Please help me ... I don't know why savedNumbers.Clear() isn't working at that line.

EDIT: Thanks, problem is solved.

user1171498
  • 23
  • 1
  • 8

5 Answers5

2

You can't modify the collection while enumerating over it. So, the exception is valid. Clear once you are done with enumerating it.

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
0

You can't modify a list while iterating that same list.

0

You are clearing the list in the middle of enumerating it. You cannot modify the list when you are in the process of enumeration.

int answer = 0;
foreach(int getal in savedNumbers)
{
    Console.WriteLine(getal);
    answer = answer + getal;
}
savedNumbers.Clear(); 
return answer;
didster
  • 882
  • 5
  • 9
0

While iterating you cannot change the list/collection, while you can do the same using loop as stated below:

for (int i = 0 i < savedNumbers.Count; i++)
{
    var getal = savedNumbers[i];
    Console.WriteLine(getal);
    answer = answer + getal;
    savedNumbers.Clear();
}

You can't modify a collection while enumerating over it. That rule exists even without threading issues considered. From MSDN:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

References:

  1. Modifying .NET Dictionary while Enumerating through it
  2. Why does enumerating through a collection throw an exception but looping through its items does not
Community
  • 1
  • 1
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
0

Msdn says: The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects

Sanja Melnichuk
  • 3,465
  • 3
  • 25
  • 46