Skip to content

Roslyn fails to apply inferred type arguments' nullability after ?. access #33289

@TessenR

Description

@TessenR

Version Used:
Microsoft Visual Studio Enterprise 2019 Preview
Version 16.0.0 Preview 2.1
VisualStudio.16.Preview/16.0.0-pre.2.1+28529.54
Microsoft .NET Framework
Version 4.7.03056

Steps to Reproduce:

Compile and run the following code:

#nullable enable
struct C<T>
{
  public T FieldWithInferredAnnotation;
  public string? ExplicitlyAnnotatedField;
}
class C
{
  static void Main()
  {
    Test(null);
    System.Console.ReadKey();
  }

  static void Test(string? s)
  {
    var nc = M(s);
    nc?.FieldWithInferredAnnotation.ToString(); // no warnings, the program crashes at runtime on this line
  }

  public static C<T>? M<T>(T t) => new C<T>();
}

Expected Behavior:
Warning CS8602 Possible dereference of a null reference. reported for at the line nc?.FieldWithInferredAnnotation.ToString()

Actual Behavior:
Roslyn fails to warn about possible dereference of a null reference in case of ?. access to a generic field. The program crashes at runtime with a NullReferenceException on the line that doesn't have any warnings.

Notes
It looks like Roslyn fails to apply type arguments with inferred nullability after unwrapping a generic struct from Nullable<T> with ?. access.
Explicitly annotated fields e.g. nc?.ExplicitlyAnnotatedField.ToString() and direct unwraps from Nullable<T> via its .Value property e.g. nc.Value.FieldWItnInferredAnnotation.ToString() have correct warnings.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Active/Investigating

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions