Skip to content

Instantly share code, notes, and snippets.

@einaros
Created October 8, 2010 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save einaros/616483 to your computer and use it in GitHub Desktop.
Save einaros/616483 to your computer and use it in GitHub Desktop.
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