11,428,497 members (64,188 online)
Tip/Trick

# Who knows Enumerable.Range(...)?

, 14 Apr 2013 CPOL
 Rate this:
Make loops behave deterministic-by-construction

## Introduction

I quite often see constructs like:

```for(int n = 0; n < len; ++n)
{
//... some more or less complex conditional control flow...
n = 5; // causes the loop to never terminate if len is greater than 5
//... some more code ...
}```

This is a legal language construct, but it introduces the danger of non-determinism.

This tip aims to show some deterministic alternatives to that plain `for` loop.

## Using the Code

If you need to loop over some range of integer, consider using the Enumerable.Range[^] based `foreach` loop instead:

```using System.Linq;
...
foreach (int n in Enumerable.Range(0, len))
{
...
}```

This guarantees that it iterates over all elements in strict sequence. Another benefit is that you cannot assign any other value to the loop variable `n`. E.g.

```foreach (int n in Enumerable.Range(0, len))
{
n = 5; // Compiler error!
}```

Note: `Enumerable.Range(...)` is not from, to, but from, count:

```//
// Summary:
//     Generates a sequence of integral numbers within a specified range.
//
// Parameters:
//   start:
//     The value of the first integer in the sequence.
//
//   count:
//     The number of sequential integers to generate.
//
// Returns:
//     An IEnumerable<Int32> in C# or IEnumerable(Of Int32) in Visual Basic that
//     contains a range of sequential integral numbers.
//
// Exceptions:
//   System.ArgumentOutOfRangeException:
//     count is less than 0.-or-start + count -1 is larger than System.Int32.MaxValue.
public static IEnumerable<int> Range(int start, int count);```

## Alternatives

One could also build his own iterator functions (see also C# Iterator Pattern demystified[^]). E.g.

```public static IEnumerable<int> CountUp(int n, int count)
{
while (count-- > 0) yield return n++;
}
public static IEnumerable<int> CountDown(int n, int count)
{
while (count-- > 0) yield return n--;
}```

When used like this...

```foreach (int n in CountUp(0, 5)) Console.WriteLine(n);
foreach (int n in CountDown(100, 5)) Console.WriteLine(n);```

...results in:

```0
1
2
3
4
100
99
98
97
96```

You can define any complexity of traversing sequence in that function and let the `foreach`-loop terminate deterministically, based on that sequence.

Try to avoid plain `for (...)` loops and replace by some deterministic loop alternative like:

• `foreach( ... Range(...))`
• `foreach( ... CountUp(...))`
• etc.

Other alternatives are Linq iterations like Enumerable.Aggregate[^] etc. But these are a bit more advanced.

## History

• 2012-04-18 First version
• 2012-04-19 Added hand-crafted `CountUp`/`CountDown `functions
• 2013-04-14 Fixed some broken HTML markup in C# code generics

## Share

Founder eXternSoft GmbH
Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

 First Prev Next
 Re: My vote of 5 Andreas Gieriet23-Apr-13 13:59 Andreas Gieriet 23-Apr-13 13:59
 overcoming "from, count" Matt T Heffron15-Apr-13 8:38 Matt T Heffron 15-Apr-13 8:38
 Re: overcoming "from, count" Andreas Gieriet15-Apr-13 11:33 Andreas Gieriet 15-Apr-13 11:33
 Re: overcoming "from, count" Matt T Heffron15-Apr-13 11:43 Matt T Heffron 15-Apr-13 11:43
 Re: overcoming "from, count" Andreas Gieriet15-Apr-13 13:02 Andreas Gieriet 15-Apr-13 13:02
 Re: overcoming "from, count" Matt T Heffron15-Apr-13 13:09 Matt T Heffron 15-Apr-13 13:09
 Another readability optimization paul.vencill15-Apr-13 2:09 paul.vencill 15-Apr-13 2:09
 Re: Another readability optimization Andreas Gieriet15-Apr-13 6:50 Andreas Gieriet 15-Apr-13 6:50
 Thoughts PIEBALDconsult14-Apr-13 16:30 PIEBALDconsult 14-Apr-13 16:30
 My vote of 5 Kenneth Haugland3-Sep-12 14:53 Kenneth Haugland 3-Sep-12 14:53
 Re: My vote of 5 Andreas Gieriet3-Sep-12 21:21 Andreas Gieriet 3-Sep-12 21:21
 Pros and Cons and ... Jani Giannoudis18-Apr-12 13:26 Jani Giannoudis 18-Apr-12 13:26
 Pros: - deterministic - Readability for non-numeric ranges Cons: - Performance: http://madprops.org/blog/for-vs-foreach-performance/[^] - Readability for numeric ranges - different pattern for ascending/descending iterations - requires Linq As a good coding practice, you never change the iteration variable within a loop. Cheers, Jani Giannoudis Meerazo.com - Resource Sharing Made Easy | Co-founder
 Re: Pros and Cons and ... [modified] Andreas Gieriet18-Apr-12 22:22 Andreas Gieriet 18-Apr-12 22:22
 Your problem is not the for... Paulo Zemek18-Apr-12 10:48 Paulo Zemek 18-Apr-12 10:48
 Re: Your problem is not the for... Andreas Gieriet18-Apr-12 11:56 Andreas Gieriet 18-Apr-12 11:56
 Re: Your problem is not the for... Paulo Zemek18-Apr-12 15:10 Paulo Zemek 18-Apr-12 15:10
 Re: Your problem is not the for... Andreas Gieriet18-Apr-12 19:05 Andreas Gieriet 18-Apr-12 19:05
 Re: Your problem is not the for... TimothyP22-Apr-13 9:26 TimothyP 22-Apr-13 9:26
 Re: Your problem is not the for... Andreas Gieriet22-Apr-13 9:45 Andreas Gieriet 22-Apr-13 9:45
 Last Visit: 31-Dec-99 19:00     Last Update: 3-May-15 2:12 Refresh 1