≡ Menu

Find the Bug – C# and Infinite Loops with Collections

See if you can spot the problem with the following C# code:

var list = new List { "fish", "and", "chips" };
for (int i = 0; i < list.Count; i++) {   list.Add(list[i].ToUpper()); }

As the title points out, this will cause an infinite loop, and will eat up all of your memory. What happens is that we iterate through the list once (i=0; list.Count = 3) and then add an element to the list. So the next loop we have (i=1; list.Count = 4). This is because anything in the parenthesis of the for operator will be evaluated every loop.

There are three options:

  1. Don't modify the list you are working on
  2. Save off list.Count to a variable and use that variable in the loop
  3. Use generics and/or Linq instead of manually walking the list yourself.

And the code was a dummy example code, nothing in use in any real system.

Comments on this entry are closed.