13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

168 CHAPTER 6 Implement<strong>in</strong>g iterators the easy wayConsole.WriteL<strong>in</strong>e ("Start<strong>in</strong>g to iterate");while (true){Console.WriteL<strong>in</strong>e ("Call<strong>in</strong>g MoveNext()...");bool result = iterator.MoveNext();Console.WriteL<strong>in</strong>e ("... MoveNext result={0}", result);if (!result){break;}Console.WriteL<strong>in</strong>e ("Fetch<strong>in</strong>g Current...");Console.WriteL<strong>in</strong>e ("... Current result={0}", iterator.Current);}List<strong>in</strong>g 6.5 certa<strong>in</strong>ly isn’t pretty, particularly around the iteration side of th<strong>in</strong>gs. Inthe normal course of events we’d just use a foreach loop, but to show exactly what’shappen<strong>in</strong>g when, I had to break the use of the iterator out <strong>in</strong>to little pieces. Thiscode broadly does what foreach does, although foreach also calls Dispose at theend, which is important for iterator blocks, as we’ll see shortly. As you can see,there’s no difference <strong>in</strong> the syntax with<strong>in</strong> the method even though this time we’rereturn<strong>in</strong>g IEnumerable <strong>in</strong>stead of IEnumerator. Here’s the output fromlist<strong>in</strong>g 6.5:Start<strong>in</strong>g to iterateCall<strong>in</strong>g MoveNext()...Start of GetEnumerator()About to yield 0... MoveNext result=TrueFetch<strong>in</strong>g Current...... Current result=0Call<strong>in</strong>g MoveNext()...After yieldAbout to yield 1... MoveNext result=TrueFetch<strong>in</strong>g Current...... Current result=1Call<strong>in</strong>g MoveNext()...After yieldAbout to yield 2... MoveNext result=TrueFetch<strong>in</strong>g Current...... Current result=2Call<strong>in</strong>g MoveNext()...After yieldYield<strong>in</strong>g f<strong>in</strong>al value... MoveNext result=TrueFetch<strong>in</strong>g Current...... Current result=-1Call<strong>in</strong>g MoveNext()...End of GetEnumerator()... MoveNext result=FalseThere are various important th<strong>in</strong>gs to note from this output:Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!