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
18.99k stars 4.03k forks source link

Nullable reference types: while ((x = Some()) != null) not considered a null check #9931

Closed bkoelman closed 6 years ago

bkoelman commented 8 years ago

I have been playing with nullable reference types, which is already working remarkably great! To try it out, I have patched up my analyzer to convert Resharper's (Item)NotNull/CanBeNullAttribute annotations to nullable reference types. Then ran that on an actual annotated codebase.

During that process I discovered some oddities, which I'll create issues for here.

Version Used: Built from source, branch NullableReferenceTypes (commit https://github.com/dotnet/roslyn/commit/8553cdac75c2b0901e8ae401aaa23022f0689935)

Steps to Reproduce: The next block of code raises warning 8202: Possible dereference of a null reference:

    public class Test
    {
        public void Add(ArraySegment<byte> bufferSegment)
        {
            byte[]? packet;
            while ((packet = ConsumeNextPacket(ref bufferSegment)) != null)
            {
                int length = packet.Length; // CS8202
            }
        }

        public byte[]? ConsumeNextPacket(ref ArraySegment<byte> bufferSegment)
        {
            throw new NotImplementedException();
        }
    }

Expected Behavior: No CS8202 warning, because inside the while loop, it is impossible for packet to be null (because packet != null is a condition to enter the loop).

Actual Behavior: CS8202 warning on the packet variable inside the while loop.

@AlekseyTs

bkoelman commented 6 years ago

This bug is fixed in Nullable Reference Types Preview 3/6/18.

bkoelman commented 6 years ago

/cc @cston Feel free to close this issue.