0

I'm trying to implement a snippet where we can loop through a dynamic list of objects.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var l = new List<int>();
        l.Add(1);
        l.Add(2);
        l.Add(3);
        l.Add(4);

    foreach(var i in l){
        Console.WriteLine(i);   
        if(i==3){
            l.Add(5);
        }

    }

}

}

This is throwing below run time error.

1
2
3
Run-time exception (line 15): Collection was modified; enumeration operation may not execute.

Stack Trace:

[System.InvalidOperationException: Collection was modified; enumeration operation may not execute.]
  at Program.Main(): line 15

Any help is appreciated. Thanks.

j. Doe
  • 3
  • 5

1 Answers1

2

This can be achieved by replacing foreach with for loop

for (var i = 0; i < l.Count; i++)
{
     Console.WriteLine(l[i]);
     if (l[i] == 3)
     {
        l.Add(5);
     }
}
BetterLateThanNever
  • 886
  • 1
  • 9
  • 31