dotnet 6.0 / C#10
VisualStudio and VS Code
We have noticed some cases were S2259 isn’t being reported consistently. It took some digging but found the issue.
I believe it’s this from 2019: Investigate why S2259 does not always trigger on C# 8 code · Issue #2601 · SonarSource/sonar-dotnet (github.com)
I commented there as well.
Adding a single null conditional operator or single null coalescing operator will suppress all S2259 warnings in the entire method - related or not.
This hides many potential null-ref issues in our codebase.
See the following example:
public static class Example
{
public class Test
{
public string Uri { get; set; }
}
public static void Method()
{
// change just one of these member accesses on the lines commented w/ S2259
// to use null conditional operator and it suppresses all other occurrences of S2259
// warnings in the method - e.g. ia?.Length
int[] ia = null;
Console.WriteLine(ia.Length); // S2259
Test[] ta = Array.Empty<Test>();
var test1 = ta.FirstOrDefault();
Console.WriteLine(test1.Uri); // S2259
Test test2 = null;
Console.WriteLine(test2.Uri); // S2259
// A single null coalescing will suppress all S2259 errors in the method
// Uncomment the following
// var test3 = test2 ?? new ();
// Console.WriteLine(test3.Uri);
}
}