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: 258

Filed under:
|
|

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

  1. You can't use the yield keyword
  2. Use only C# itself directly - no IL code, no constructing dynamic assemblies etc.
  3. 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.
  4. 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

Is it possible to implement an infinite IEnumerable without using yield with only C# code?

Posted by sinelaw on Stack Overflow See other posts from Stack Overflow or by sinelaw
Published on 2013-11-07T03:27:33Z Indexed on 2013/11/07 3:54 UTC
Read the original article Hit count: 258

Filed under:
|
|

Edit: Apparently off topic...moving to Programmers.StackExchange.com.

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

  1. You can't use the yield keyword
  2. Use only C# itself directly - no IL code, no constructing dynamic assemblies etc.
  3. 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.
  4. 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 :)

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ