dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.02k stars 4.03k forks source link

Foreach ignores nullability attributes on return type of GetEnumerator #43940

Open YairHalberstadt opened 4 years ago

YairHalberstadt commented 4 years ago

Version Used: VS 16.6 preview 1

Steps to Reproduce:

using System;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

#nullable enable
public class A
{
    [return: MaybeNull]
    public IEnumerator<int> GetEnumerator() => throw null!;
}

public class B
{
    [return: NotNull]
    public IEnumerator<int>? GetEnumerator() => throw null!;
}

public static class C {
    public static void M() {
        foreach (var a  in new A())
        {
        }

        foreach (var b  in new B())
        {
        }
    }
}

Expected Behavior: warning "Dereference of a possible null reference" on foreach (var a in new A()) and not on foreach (var b in new B())

Actual Behavior: warning "Dereference of a possible null reference" on foreach (var b in new B()) and not on foreach (var a in new A())

YairHalberstadt commented 4 years ago

I have a fix in the extension foreach branch:

https://github.com/dotnet/roslyn/pull/43050