This is an old revision of the document!
IEnumerator
Notes on the underlying implementation of C# generators (which are used in Unity for coroutines).
You can use SharpLab to view the decompiled C# from a simple generator, to help understand the transformation that is happening. Both .NET and Mono do seem to use the same compiler transformation when turning Generators into anonymous IEnumerator classes. example
States
Generators are compiled down into a state machine, with states for each yield return
point. ie:
0: The generator has not yet been run.
1: The generator has paused on the first yield return.
2: The generator has paused on the second yield return.
-1: The generator has finished, the generator exited early, or the generator threw an exception.
The state value is set in a field private int <>1state on the generated IEnumerator class:
<code c#>
[CompilerGenerated]
private sealed class <M>d0 : IEnumerator<object>, IDisposable, IEnumerator
{
private int <>1state;
private object <>2current;
public C <>4this;
snipped
</code>
===== Lambda function DisplayClass classes are initialized at the start of the function =====
The following code, in SharpLab decompiles it as:
<code c#>
using System;
using System.Collections;
public class C {
public IEnumerator M() {
int x = 5;
yield return Test1)