SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
755 stars 223 forks source link

Fix S2955 FP: Comparing nullable type with null #9493

Open paulhickman-ec opened 3 days ago

paulhickman-ec commented 3 days ago

Description

The following code causes S2955. However comparing to default(T) instead of null as the rule suggests gives a compiler error. Even if it did compile, if T was int then default(T) would be zero which gives different behavior than comparing T? to null.

Repro steps

public bool Foo<T>(Func<T?> bar) where T : notnull
{
    T? t = bar();
    return t == null;
}

Expected behavior

Rule does not fire

Actual behavior

Rule does fire

Known workarounds

Ignore the rule

Related information

zsolt-kolbay-sonarsource commented 2 days ago

Thank you for reporting the issue. Confirmed as False Positive.