There are answers that claim that you cannot achieve with foreach. This statement is false, all you have to do is write a custom class using a custom enumerator.
public class CustomList : IEnumerable<int> { readonly List<int> list = new List<int>{1,2,3,4}; private int now = 0; public void Add(int n) { list.Add(n); } public IEnumerator<int> GetEnumerator() { while (now<list.Count) { yield return list[now]; now++; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
Now the following code fragment will print 1,2,3,4 and 100 on the screen:
var list = new CustomList(); foreach (int n in list) { if(n==1) list.Add(100); Console.WriteLine(n); }
But I write this only as a proof of concept. You do not want to do this. If you only add new elements on the flip side, use Queue as others have said. If you will always add new items to the forefront, use Stack. If you need both options, write your own LinkedList class with Dequeue (= Pop), Enqueue, and Push operations, use something like:
while(list.notEmpty()) var item = list.Dequeue();
and all of you are tuned. (You can even write your own custom repeater to use it with foreach, but we destroy the list when we go, so this is contrary to the spirit of enumerations and why bother anyway)
source share