Skip to content

Roslyn doesn't understand pattern-matching null check for properties #39264

@TessenR

Description

@TessenR

Version Used:

Branch master (23 Sep 2019)
Latest commit 89b4f60 by Charles Stoner:
Allow conversion of collection initializer Add extension method this arg (#38732)

Steps to Reproduce:

Compile the following code:

#nullable enable
class C
{
    string? field;

    void M1(C c)
    {
        if (c.field == null) return;
        
        c.field.ToString();
    }
    
    void M2(C c)
    {
        if (c is { field: null }) return;
        
        c.field.ToString(); // incorrect CS8602
    }
}

sharplab

Expected Behavior:
Both methods report no warnings; If c.field is null method returns in both cases before using it.

Actual Behavior:
M2 has an incorrect warning CS8602: Dereference of a possibly null reference reported for c.field.ToString()

Notes
It's actually even worse since such null checks makes Roslyn think that field is checked for null but does not update it to non-null on the false branch. Consequently Roslyn reports the warning even if field is declared as non-nullable string
i.e.

#nullable enable
class C
{
    string field;
    
    void M2(C c)
    {
        if (c is { field: null }) return;
        
        c.field.ToString(); // incorrect CS8602
    }
}

Note that current behavior is quite annoyting since it does not allow me to hande nulls hvia separate patterns in switches e.g.:

#nullable enable
class C
{
    string? field;
    
    void M2(C c)
    {
        switch (c)
        {
            case { field: null }: break;
            case var copy:
            {
              copy.field.ToString(); // CS8602
              c.field.ToString(); // CS8602
              break;
            }
        }
    }
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions