Open
Description
Background and motivation
I would like to implement a more convenient and readable way to pass through all the elements of the range than
foreach (int i in Enumerable.Range(1, 5))
Console.WriteLine(i);
and
for (var i = 1; i < 5; i++)
Console.WriteLine(i);
I immediately remembered the Range type (which can be defined using a..b
), and tried to use it inside foreach loop, but as it turned out, it does not contain an implementation of IEnumerable
API Proposal
namespace System.Collections.Generic;
public class Range : IEnumerable<T>
{
public IEnumerator<int> GetEnumerator()
{
// something like
for (var i = range.Start.Value; i < range.End.Value; i++)
yield return i;
}
}
API Usage
foreach (var i in 1..10){
Console.WriteLine(i);
}
Risks
You may need to add a check for the not null of Start and End fields (or set their values to default if they null), which can add a couple of extra instructions for each loop that uses Range. However, this can be fixed by checking Start and End fields at compile time and (possibly) adding a new type, which will be a limited range, and which can be implicitly converted to a regular range