dotnet/roslyn

Explicit conversion in foreach is incorrect

Open

#35,918 opened on May 23, 2019

View on GitHub
 (0 comments) (0 reactions) (0 assignees)C# (4,257 forks)batch import
Area-CompilersBughelp wanted

Repository metrics

Stars
 (20,414 stars)
PR merge metrics
 (Avg merge 6d 17h) (256 merged PRs in 30d)

Description

See https://github.com/dotnet/roslyn/pull/35095#discussion_r277894589 for context

For an explicit conversion from foreach, the expected value should be NoConversion when the current type is explicit and the enumerable type is unknown

[@gafter added] The context is a test with the source code

class C1
{
}

class C2
{
    public void M() 
    {
        var c = new C1();
        foreach (string item in c.Items)
        {
        }
}

which tests

            var comp = CreateCompilation(source);
            var tree = comp.SyntaxTrees.Single();
            var model = comp.GetSemanticModel(tree);

            var root = tree.GetRoot();
            var foreachSyntaxNode = root.DescendantNodes().OfType<ForEachStatementSyntax>().Single();
            var foreachSymbolInfo = model.GetForEachStatementInfo(foreachSyntaxNode);

            Assert.Equal(Conversion.UnsetConversion, foreachSymbolInfo.CurrentConversion);
            Assert.True(foreachSymbolInfo.CurrentConversion.Exists);
            Assert.False(foreachSymbolInfo.CurrentConversion.IsImplicit);

and the comment was

I'd expect the conversion to be Conversion.NoConversion (and Exists to be false).

I think that was changed by PR https://github.com/dotnet/roslyn/pull/33648 which introduced UnsetConversion, but not intentionally.

Contributor guide