Consider this code snippet:
class Program {
static void Main(string[] args) {
Console.WriteLine(Test().ToString());
}
static IEnumerable<char> Test() {
foreach (var ch in "test")
yield return ch;
}
static IEnumerable<char> TestOk() {
return "test";
}
}
Test().ToString() returns “ConsoleApplication1.Program+d__0” instead of expected “test”.
Test() method isn’t even executed – just returns its name! The second method TestOk() works just fine.
What is going on?
It’s printing the ToString method on the IEnumerable implementation generated by the compiler – Iterators are just syntactic sugar – a real implementation of IEnumerable is generated.