Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created June 20, 2014 16:11
Show Gist options
  • Save AlexArchive/0e0b6e994f5047b1d2fc to your computer and use it in GitHub Desktop.
Save AlexArchive/0e0b6e994f5047b1d2fc to your computer and use it in GitHub Desktop.
private static IEnumerable<string> Something()
{
yield return "Something() One";
yield return "Something() Two";
yield return "Something() Three";
}
// When the compiler encounters an iterator block it emits a nested type for the state machine similar to this:
private static IEnumerable<string> Something()
{
SomethingEnumerator somethingEnumerator = new SomethingEnumerator(2);
return somethingEnumerator;
}
private sealed class SomethingEnumerator : IEnumerable<string>, IEnumerator<string>
{
private int state;
private int initialThreadId;
public string Current { get; private set; }
object IEnumerator.Current
{
get { return Current; }
}
public SomethingEnumerator(int state)
{
this.state = state;
initialThreadId = Environment.CurrentManagedThreadId;
}
public IEnumerator<string> GetEnumerator()
{
SomethingEnumerator somethingEnumerator;
if (Environment.CurrentManagedThreadId == initialThreadId && state == 2)
{
state = 0;
somethingEnumerator = this;
}
else
{
somethingEnumerator = new SomethingEnumerator(0);
}
return somethingEnumerator;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool MoveNext()
{
switch (state)
{
case 0:
state = -1;
Current = "Something() One";
state = 1;
return true;
case 1:
state = -1;
Current = "Something() Two";
state = 2;
return true;
case 2:
state = -1;
Current = "Something() Three";
state = 3;
return true;
case 3:
state = -1;
break;
}
return false;
}
public void Reset()
{
throw new NotSupportedException();
}
public void Dispose()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment