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.