I am watching Jon Skeet's Copenhagen C# talk videos and I ended up with this code.
QUESTION:
What is happening after the code prints Finished. I mean why is iterator.MoveNext()
failing?
CODE:
class IteratorBlocks
{
public static IEnumerable<string> GetStringsForever()
{
string current = "";
char nextChar = 'a';
try
{
while (true)
{
current += nextChar;
nextChar++;
if (nextChar > 'z')
{
nextChar = 'a';
}
yield return current;
}
}
finally
{
Console.WriteLine("Finished");
}
}
}
class Program
{
static void Main(string[] args)
{
IEnumerable<string> strings = IteratorBlocks.GetStringsForever();
IEnumerator<string> iterator = strings.GetEnumerator();
for (int i = 0; i < 10; i++)
{
iterator.MoveNext();
Console.WriteLine(iterator.Current);
}
/*
I am not able to get what the code is doing beyond this line?
*/
iterator.Dispose();
for (int i = 0; i < 10; i++)
{
iterator.MoveNext();
Console.WriteLine(iterator.Current);
}
}
}
OUTPUT:
a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
Finished
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij
abcdefghij