Looping through a dynamic List of objects
<p>I'm trying to implement a snippet where we can loop through a dynamic list of objects. </p>

<pre><code>using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var l = new List&lt;int&gt;();
        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);
        }

    }

}

}
</code></pre>

<p>This is throwing below run time error.</p>

<pre><code>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
</code></pre>

<p>Any help is appreciated. Thanks.</p>