You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The following program results in a warning about passing a possible null argument to DoSomething. As far as I can see there is no possibility the argument could be null.
using System;
using System.Collections.Generic;
var ids = GetIds();
if ((ids?.Count ?? 0) == 0)
{
return;
}
DoSomething(ids);
static void DoSomething(List<string> ids)
{
Console.WriteLine(ids.Count);
}
static List<string>? GetIds()
{
return null;
}
Replacing if ((ids?.Count ?? 0) == 0) with if (ids is null || ids.Count == 0) (or various other pattern matching techniques to accomplish the same thing) makes the warning go away, even though Sharplab says they lower to the same code.
We have this pattern in many places in a large codebase and it makes turning on nullable checks difficult. It would be much nicer if the compiler could detect that the variable cannot be null in this case.
The text was updated successfully, but these errors were encountered:
Closing out. The compiler doesn't track the null relationship through arithmetic expressions (like (ids?.Count ?? 0) and then teh ==0).
You can write this as:
if(ids isnull|| ids.Count ==0){return;}
or
if(ids is not { Count:>0})return;
It would be much nicer if the compiler could detect that the variable cannot be null in this case.
We've looked at this sort of relationship before and decided the large increase in analysis complexity is not worth it, given hte simple and idiomatic transforms available.
Repro
The following program results in a warning about passing a possible null argument to DoSomething. As far as I can see there is no possibility the argument could be null.
Replacing
if ((ids?.Count ?? 0) == 0)
withif (ids is null || ids.Count == 0)
(or various other pattern matching techniques to accomplish the same thing) makes the warning go away, even though Sharplab says they lower to the same code.We have this pattern in many places in a large codebase and it makes turning on nullable checks difficult. It would be much nicer if the compiler could detect that the variable cannot be null in this case.
The text was updated successfully, but these errors were encountered: