Question
Why do we get possible dereference null reference warning, when null reference does not seem to be possible?
Having read this question on HNQ, I went on to read about Nullable Reference Types in C# 8, and made some experiments.
I'm very aware that 9 times out of 10, or even more often, when someone says "I found a compiler bug!" this is actually by design, and their own misunderstanding. And since I started to look into this feature only today, clearly I do not have very good understanding of it. With this out of the way, lets look at this code:
#nullable enable
class Program
{
static void Main()
{
var s = "";
var b = s == null; // If you comment this line out, the warning on the line below disappears
var i = s.Length; // warning CS8602: Dereference of a possibly null reference
}
}
After reading the documentation I linked to above, I would expect the s == null
line to give me a warning—after all s
is clearly non-nullable, so comparing it to null
does not make sense.
Instead, I'm getting a warning on the next line, and the warning says that s
is possible a null reference, even though, for a human, it's obvious it is not.
More over, the warning is not displayed if we do not compare s
to null
.
I did some Googling and I hit a GitHub issue, which turned out to be about something else entirely, but in the process I had a conversation with a contributor that gave some more insight in this behaviour (e.g. "Null checks are often a useful way of telling the compiler to reset its prior inference about a variable's nullability."). This still left me with the main question unanswered, however.
Rather than creating a new GitHub issue, and potentially taking up the time of the incredibly busy project contributors, I'm putting this out to the community.
Could you please explain me what's going on and why? In particular, why no warnings are generated on the s == null
line, and why do we have CS8602
when it does not seem like a null
reference is possible here? If nullability inference is not bullet-proof, as the linked GitHub thread suggests, how can it go wrong? What would be some examples of that?