Odd Method Behavior - ToString Functions

Consider this piece of code:

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 the expected "test".

Test() method does not even execute - it just returns its name! The second TestOk() method works fine.

What's happening?

+4
source share
4 answers

It prints the ToString method in the IEnumerable implementation generated by the compiler. Iterators are just syntactic sugar. A real implementation of IEnumerable is created.

+7
source

The Test () method returns IEnumerable (char), which in this case is a generated compiler. The ToString () method is the default value for the object and returns the type name as well as the generated compiler.

+2
source

The yeild return method is handled differently than the compiler - if you check the compiled assembly using a reflector, then what happens here becomes a little clearer:

 private static IEnumerable<char> Test() { return new <Test>d__0(-2); } 

Wheras TestOk returns a string, Test instead returns the class that the compiler generates for you. What you see is a string representation of this class by default.

+2
source

Other answers explained the current behavior, but if you want the expected behavior, instead of using ToString (), you can convert the IEnumerable<char> to an array and use the String constructor, which takes char[] :

 Console.WriteLine(new string(Test().ToArray())); 
0
source

All Articles