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.
The Test() method returns an IEnumerable(char) which in this case is a compiler generated object. It's ToString() method is the default for an object and returns the type name, also compiler generated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With