Created
October 8, 2010 07:57
-
-
Save einaros/616483 to your computer and use it in GitHub Desktop.
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
namespace ConsoleTest | |
{ | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
internal class Program | |
{ | |
#region Methods: private | |
static void Main(string[] args) | |
{ | |
var p = new Producer(); | |
foreach(var s in p.RepeatForever()) | |
{ | |
Console.Out.WriteLine(s); | |
Console.ReadKey(); | |
} | |
} | |
#endregion | |
} | |
internal class Producer : IEnumerable<string> | |
{ | |
public IEnumerator<string> GetEnumerator() | |
{ | |
Console.Out.WriteLine("Enumerator called - I may have side effets"); | |
yield return "Foo"; | |
yield return "Bar"; | |
yield return "Baz"; | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
} | |
public static class IEnumerableExtensions | |
{ | |
public static IEnumerable<T> RepeatForever<T>(this IEnumerable<T> self) | |
{ | |
var list = new List<T>(); | |
foreach(var elem in self) | |
{ | |
list.Add(elem); | |
yield return elem; | |
} | |
for(int i = 0;; i = (i + 1) % list.Count) | |
yield return list[i]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment