Is it possible to implement an infinite IEnumerable without using yield with only C# code?
Posted
by
sinelaw
on Programmers
See other posts from Programmers
or by sinelaw
Published on 2013-11-07T03:48:05Z
Indexed on
2013/11/07
4:12 UTC
Read the original article
Hit count: 369
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 :)
© Programmers or respective owner