Skip to content

Reinfer GetEnumerator type based on input type. #35151

@333fred

Description

@333fred
using System.Collections;
class C
{
    void M1(IEnumerator e)
    {
        var enumerable1 = Create(e);
        foreach (var i in enumerable1)
        {
        }

        e = null; // 1
        var enumerable2 = Create(e);
        foreach (var i in enumerable2) // 2
        {
        }
    }

    void M2(IEnumerator? e)
    {
        var enumerable1 = Create(e);
        foreach (var i in enumerable1) // 3
        {
        }

        if (e == null) return;
        var enumerable2 = Create(e);
        foreach (var i in enumerable2)
        {
        }
    }
    static Enumerable<T> Create<T>(T t) where T : IEnumerator? => throw null!;
}

class Enumerable<T> where T : IEnumerator?
{
    public T GetEnumerator() => throw null!;
}

This test should have warnings on the foreachs indicated. In addition to the GetEnumerator reinference, this also exposes that when we do the visit of the foreach expression, we need to explicitly remove implicit conversions from the expression and call ApplyConversion ourselves.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions