Is it possible to implement an infinite IEnumerable without using yield with only C# code?
- by sinelaw
This isn't a practical problem, it's more of a riddle.
Problem
I'm curious to know if there's a way to implement something equivalent to the following, but without using yield:
IEnumerable<T> Infinite<T>()
{
while (true) { yield return default(T); }
}
Rules
You can't use the yield keyword
Use only C# itself directly - no IL code, no constructing dynamic assemblies etc.
You can only use the basic .NET lib (only mscorlib.dll, System.Core.dll? not sure what else to include). However if you find a solution with some of the other .NET assemblies (WPF?!), I'm also interested.
Don't implement IEnumerable or IEnumerator.
Notes
The closest I've come yet:
IEnumerable<int> infinite = null;
infinite = new int[1].SelectMany(x => new int[1].Concat(infinite));
This is "correct" but hits a StackOverflowException after 14399 iterations through the enumerable (not quite infinite).
I'm thinking there might be no way to do this due to the CLR's lack of tail recursion optimization. A proof would be nice :)