Cannot print to console using yield return

In the tests below, I cannot get Console.WriteLine to actually print when using return returns. I am experimenting with the return of profitability, and I understand that I have something missing in my understanding of this, but I can not understand what it is. Why aren't PrintAllYield lines printed?

code:

 class Misc1 { public IEnumerable<string> PrintAllYield(IEnumerable<string> list) { foreach(string s in list) { Console.WriteLine(s); // doesn't print yield return s; } } public void PrintAll(IEnumerable<string> list) { foreach(string s in list) { Console.WriteLine(s); // surely prints OK } } } 

Test:

 [TestFixture] class MiscTests { [Test] public void YieldTest() { string[] list = new[] { "foo", "bar" }; Misc1 test = new Misc1(); Console.WriteLine("Start PrintAllYield"); test.PrintAllYield(list); Console.WriteLine("End PrintAllYield"); Console.WriteLine(); Console.WriteLine("Start PrintAll"); test.PrintAll(list); Console.WriteLine("End PrintAll"); } } 

Output:

 Start PrintAllYield End PrintAllYield Start PrintAll foo bar End PrintAll 1 passed, 0 failed, 0 skipped, took 0,39 seconds (NUnit 2.5.5). 
+4
source share
1 answer

You must actually list the returned IEnumerable to see the result:

  Console.WriteLine("Start PrintAllYield"); foreach (var blah in test.PrintAllYield(list)) ; // Do nothing Console.WriteLine("End PrintAllYield"); 

When you use the yield return keyword, the compiler will build a state machine for you. Its code will only run when you actually use it to iterate the returned enumerated.

Is there a specific reason why you are trying to use yield return to print a string s sequence? This is not exactly the purpose of this function, which is to simplify the creation of sequence generators, rather than listing already generated sequences. foreach is the preferred method for the latter.

+11
source

All Articles