Not all IEnumerable<T> are equal

Implementing IEnumerable<T> can turn out to be tricky in certain cases. Consider the following code snippet namespace Test{ class Program { static void Main(string[] args) { Consume(new List<string>() { “a”, “b”, “c” }); } static void Consume<T>(IEnumerable<T> stream) { T t1 = stream.First(); T t2 = stream.First(); Console.WriteLine(t1.Equals(t2)); } }}   As you’d expect, it prints true. Each First() call results in a call to stream.GetEnumerator(), and each such enumerator returns elements from the beginning of the list, so calling First() twice returns the same (first) element. All good so far. Here’s a tiny class. class StringGenerator { int index; … Continue reading Not all IEnumerable<T> are equal