Created
June 23, 2013 22:59
-
-
Save AlexArchive/5846845 to your computer and use it in GitHub Desktop.
The yield keyword is merely syntactic sugar. This class demonstrates what is generated under the hood when you use yield return.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
private static readonly Random _random = new Random(); | |
private static void Main() | |
{ | |
foreach (int randomNumber in GetRandomNumbers(10)) | |
Console.WriteLine(randomNumber); | |
Console.ReadKey(); | |
} | |
private static IEnumerable<int> GetRandomNumbers(int count) | |
{ | |
var ret = new RandomNumbersEnumerator(); | |
ret.Count = 10; | |
return ret; | |
} | |
#region Nested type: RandomNumbersEnumerator | |
public class RandomNumbersEnumerator : IEnumerable<int>, IEnumerator<int> | |
{ | |
public int Count; | |
public int Index; | |
private int _current; | |
private int _state; | |
#region Implementation of IEnumerable | |
public IEnumerator<int> GetEnumerator() | |
{ | |
return this; | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
#endregion | |
#region Implementation of IDisposable | |
public void Dispose() | |
{ | |
} | |
#endregion | |
#region Implementation of IEnumerator | |
public int Current | |
{ | |
get { return _current; } | |
} | |
object IEnumerator.Current | |
{ | |
get { return Current; } | |
} | |
public bool MoveNext() | |
{ | |
switch (_state) | |
{ | |
case 0: | |
{ | |
Index = 0; | |
goto case 1; | |
} | |
case 1: | |
{ | |
_state = 1; | |
if (Index == Count) | |
return false; | |
_current = _random.Next(); | |
_state = 2; | |
return true; | |
} | |
case 2: | |
{ | |
Index++; | |
goto case 1; | |
} | |
} | |
return false; | |
} | |
public void Reset() | |
{ | |
throw new NotImplementedException(); | |
} | |
#endregion | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment