Skip to content

Missing nullability warnings for [MemberNotNullWhen] parameters #48126

@TessenR

Description

@TessenR

Version Used:

Branch master (26 Sep 2020)
Latest commit 3e38d76 by CyrusNajmabadi:
Merge pull request #48002 from CyrusNajmabadi/implicitCreation

Use implicit object creation in the IDE layers.

Steps to Reproduce:

Compile and run the following code:

using System.Diagnostics.CodeAnalysis;

#nullable enable

class C
{
    public static void Main()
    {
        if (tryGetValue1(false, true, out var s1))
          s1.ToString(); // crash
    }
    
    static bool tryGetValue1(bool a, bool b, [MaybeNullWhen(false)] out string s1)
    {
        s1 = a ? "abc" : null;
        return b; // no warnings
    }
}

Expected Behavior:
Warning for return b; because s1 might be initialized to a nullable value

Actual Behavior:
No warnings. The program crashes at runtime with a NullReferenceException

Notes
Looks like Roslyn just ignores any returns of boolean variables but tries to verify e.g. returns of negated variables.
In the following code snippet all methods should have warnings but only the ones that return !a have them

using System.Diagnostics.CodeAnalysis;

#nullable enable

class C
{    
    static bool NullWhenFalseA(bool a, [MaybeNullWhen(false)] out string s1)
    {
        s1 = null;
        return a; // no warnings
    }
    
    static bool NullWhenFalseNotA(bool a, [MaybeNullWhen(false)] out string s1)
    {
        s1 = null;
        return !a; // warning
    }
    
    static bool NullWhenTrueA(bool a, [MaybeNullWhen(true)] out string s1)
    {
        s1 = null;
        return a; // no warnings
    }
    
    static bool NullWhenTrueNotA(bool a, [MaybeNullWhen(true)] out string s1)
    {
        s1 = null;
        return !a; // warning
    }
}

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Misc

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions