Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd method behavior - ToString of a function

Tags:

c#

c#-4.0

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?

like image 221
ddt Avatar asked Dec 22 '22 00:12

ddt


2 Answers

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.

like image 135
On Freund Avatar answered Dec 24 '22 13:12

On Freund


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.

like image 24
bbudge Avatar answered Dec 24 '22 14:12

bbudge