title: How does GC work with IEnumerator and yield?
body: <p>I understand that enumerators and the yield keyword can be used to help with async/staggered operations, as you can call <code>MoveNext()</code> to run the next block of code.</p>
  
  <p>However, I don't really understand what that Enumerator object is. Where does the memory in use of the scope of the Enumerator go? If you don't <code>MoveNext()</code> an Enumerator all the way, does it get GC'd eventually?</p>
  
  <p>Basically, I'm trying to keep my GC hits down, as I am potentially using a LOT of Enumerators and GC can be an issue inside Unity, especially due to the older version of Mono it uses.</p>
  
  <p>I have tried to profile this but can't wrap my head around them still. I don't understand the scoping/referencing that happens with Enumerators. I also don't understand if Enumerators are created as Objects when you create one from a function that yields.</p>
  
  <p>The following example shows my confusion better:</p>
  
  <pre><code>// Example enumerator
  IEnumerator&lt;bool&gt; ExampleFunction()
  {
      SomeClass heavyObject = new SomeClass();
      while(heavyObject.Process())
      {
          yield return true;
      }
  
      if(!heavyObject.Success)
      {
          yield return false;
      }
  
      // In this example, we'll never get here - what happens to the incomplete Enumerator
      // When does heavyObject get GC'd?
      heavyObject.DoSomeMoreStuff();
  }
  
  // example call - Where does this enumerator come from? 
  // Is something creating it with the new keyword in the background?
  IEnumerator&lt;bool&gt; enumerator = ExampleFunction();
  while(enumerator.MoveNext())
  {
      if(!enumerator.Current)
      {
          break;
      }
  }
  
  // if enumerator is never used after this, does it get destroyed when the scope ends, or is it GC'd at a later date?
  </code></pre>