Skip to content

Nullable reference types: Analysis of null checks on fields #9978

Closed
@bkoelman

Description

@bkoelman

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 8553cda)

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

public class Test
{
    private string? value;

    public void M()
    {
        if (value != null)
        {
            int i = value.Length; // CS8202
        }
    }
}

This can be worked around using:

    public void M()
    {
        string? valueSnapshot = value;
        if (valueSnapshot != null)
        {
            int i = valueSnapshot.Length; // no warning
        }
    }

Expected Behavior: The behavior is technically correct. Another thread could change the field value in-between. I cannot think of a better way, just wanted to mention this scenario, which gets somewhat annoying, as it occurs very often (in non-multithreaded code).

Actual Behavior:
CS8202 warning on the line with value.Length inside the if statement.

@AlekseyTs

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions