Reputation: 43
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?
Upvotes: 4
Views: 155
Reputation: 59149
The other answers have explained the current behavior, but if you want to get your expected behavior then instead of using ToString() you can convert the IEnumerable<char>
to an array and use the String constructor that takes a char[]
:
Console.WriteLine(new string(Test().ToArray()));
Upvotes: 0
Reputation: 86779
The yeild return method is treated differently be the compiler - if you check the compiled assembly using reflector whats going on here becomes a little clearer:
private static IEnumerable<char> Test()
{
return new <Test>d__0(-2);
}
Wheras TestOk
returns a string, Test
instead returns a class that the compiler generates for you. What you are seeing is the default string representation of that class.
Upvotes: 2
Reputation: 1137
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.
Upvotes: 2
Reputation: 4436
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.
Upvotes: 7