# question

## How can I enumerate an infinite sequence of integers in C#?

Is there a function in C# that returns an `IEnumerator` of the infinite sequence of integers `[0, 1, 2, 3, 4, 5 ...]`?

I'm currently doing

`````` Enumerable.Range (0, 1000000000).Select (x => x * x).TakeWhile (x => (x <= limit))
``````

to enumerate all squares up to `limit`. I realize that this is effective, but if there's a built-in function that just counts up from `0`, I would prefer to use it.

· 1

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Three is no built-in function but you can easily define one.

`````` public static IEnumerable Integers(int start = 0)
{
while (true) yield return start++;
}
``````

It's possible to create one:

`````` Integers().Select(x => x * x).TakeWhile(x => x <= limit)
``````

The integer variable can overflow but in your scenario might not be important.

If it is, you can change the code to throw an exception when an overflow happens.

`````` public static IEnumerable Integers(int start = 0)
{
while (true) checked { yield return start++;}
}
``````
2 Votes 2 ·

Integers are not infinite, once you get to the end, it will overflow. So essentially the best you can do this:

`````` Enumerable.Range (0, int.MaxValue).Select (x => x * x).TakeWhile (x => (x <= limit))
``````

If you want larger ranges, you could choose different types:

`````` Enumerable.Range (0, long.MaxValue).Select (x => x * x).TakeWhile (x => (x <= limit))
Enumerable.Range (0, double.MaxValue).Select (x => x * x).TakeWhile (x => (x <= limit))
``````

Note that since you're squaring the values, the above samples would overflow at some point (namely at the square root of MaxValue).

· Share

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Well, you can't really have an infinite sequence, since `int` only has 32 bits. But you can go up to `int.MaxValue`, using `Enumerable.Range(0, int.MaxValue)`. There's no built-in function for this.