dotnet / dotnet/roslyn

No nullable warning when combining static generic fields and nullable generic type instantiations

Open
#75,677 5 comments 0 reactions 0 assignees View on GitHub
Area-Compilers Feature - Nullable Reference Types untriaged
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

**Version Used**: Main from 11 Jun 2024

**Steps to Reproduce**:

The basic idea comes from the design of nullable reference types being erased and unknown to the runtime.
With a static storage in a generic type, the data for `C` and `C` is shared. However, this is neither understood nor warned about.

```
using System;
using System.Collections.Generic;

C.Instance[0] = "hi";
C.Instance[0] = null;
Console.Write(C.Instance[0].Length);

public class C {
public static Dictionary Instance {get;set;}
static C() {
Instance = new Dictionary();
}
}
```

https://sharplab.io/#v2:D4AQTAjAsAUCAMACEEAsBuWsDCAeAygC4BOAlgHYDmAfAHQCS5AzoQIbkDGApgNrwC6iALyIARAAtSozDDxEyVAPx1GLdtz6CR5AK4AbPTOwB7Zsb1daAdTKEuACjkkKNBszadeA2gBkuVQnEAShlYEABmZDBEPAAVakQAb1hEVORIlAA2RAARUg5CUlNWYgBPXApCABp4xFUPbiTKLkJ0Jhb0AF8UtKyY+yCknrS0+vUuYURyLgB3XPzC4rKK8mrEeIGZEe6YHawYIA

**Expected Behavior**:
**Any** kind of warning on using static data in generics with a nullable type instantiation.

**Actual Behavior**:
System.NullReferenceException: Object reference not set to an instance of an object.

Contributor guide

Open the contributing guide

Research direction

Start by compiling and running the provided C# reproduction, then investigate Roslyn's nullable analysis for static fields in generic types and nullable type instantiations. Done means the compiler reports some warning for the demonstrated unsafe use, with the expected behavior validated against the sample.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.