This is the first in a series of posts that I wanted to dedicate to my own coding errors, the situations where I forget some fundamental programming concept and it has me confused for minutes, hours and\or days. So I will attempt to lay bare my own gaffs and hope that this blog serves as a permanent reminder that I remain irrevocably human.
So my latest brain freeze involved an attempt to filter an Array List based on its content (using .NET 1.1), the basic premise was as follows…
ArrayList ls = new ArrayList(); ls.Add("This"); ls.Add("is"); ls.Add("a"); ls.Add("Test"); foreach (string s in ls) { if(s == "is") ls.Remove(s); }
The more discerning programmers among us will immediately realize that this for each loop will keep iterating right up until we actually remove something and then we will get this error…
System.InvalidOperationException was unhandled
Message="Collection was modified; enumeration operation may not execute."
Simply put we cannot modify collection while iterating through it, pretty obvious when you actually take the time to read the exception ;) There are several ways to resolve this, we could create a new ArrayList that we simply add to, however, I preferred using for loops, feels closer to C.
for (int i = 0; i < ls.Count; i++) { if((string)ls[i] == "is") ls.RemoveAt(i); }
I will keep going with a list of embarrassing Faux Pas until I stop committing them, that is to say, until I stop programming ;)
Comments are closed.