“LifeAfterYield” (Solution)

Answer

1
BarBaz
Copied!

Explanation

The code from the problem will be transformed in the following code (some part of the code specifically removed for better understanding):
1
private sealed class FooEnumerable :
2
IEnumerable<string>, IEnumerator<string>
3
{
4
private int state;
5
public string Current { get; private set; }
6
7
object IEnumerator.Current
8
{
9
get { return Current; }
10
}
11
12
public FooEnumerable(int state)
13
{
14
this.state = state;
15
}
16
17
public IEnumerator<string> GetEnumerator()
18
{
19
FooEnumerable fooEnumerable;
20
if (state == -2)
21
{
22
state = 0;
23
fooEnumerable = this;
24
}
25
else
26
fooEnumerable = new FooEnumerable(0);
27
return fooEnumerable;
28
}
29
30
IEnumerator IEnumerable.GetEnumerator()
31
{
32
return GetEnumerator();
33
}
34
35
bool IEnumerator.MoveNext()
36
{
37
switch (state)
38
{
39
case 0:
40
Current = "Bar";
41
state = 1;
42
return true;
43
case 1:
44
state = -1;
45
Console.WriteLine("Baz");
46
break;
47
}
48
return false;
49
}
50
51
void IEnumerator.Reset()
52
{
53
throw new NotSupportedException();
54
}
55
56
void IDisposable.Dispose()
57
{
58
}
59
}
60
61
IEnumerable<string> Foo()
62
{
63
return new FooEnumerable(-2);
64
}
65
66
void Main()
67
{
68
var enumerator = Foo().GetEnumerator();
69
while (enumerator.MoveNext())
70
Console.Write(enumerator.Current);
71
}
Copied!
Problem
Copy link