Skip to content

[API Proposal]: Implement IEnumerable<int> for Range  #90861

Open
@CREAsTIVE

Description

@CREAsTIVE

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtimeneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions