Rules for Custom Extension Methods

Hi,

I have a question about the S2259 rule (Null pointers should not be dereferenced).
We have some custom extension method like IsNullOrEmpty which is used to determine if a collection is empty or empty. In some code samples, SonarQube somehow detects these methods and does not produce bugs, but in some code samples it does not detect this method and produces bugs.
The first screenshot didn’t detect this method so it find a bug, but in the second screenshot it detected this method so there was no bug.

1-


2-

Thank you in advance.

Hi @ckonca,

The null dereference rule is based on in-proc analysis. It doesn’t know that your IsNullOrEmpty extension methods actually validates the instance. It only sees some extension method that is safe to call.

The difference in your examples depends on the state of the variable before the call that’s not visible on the screenshot. For phaseList,there’s done something that is known to cause a possible null value. While for summary, the result of Where() will never be null so the issue is not raised.

Hi @Pavel_Mikula,

I did share another code sample. I scan the this code and there was no bug.
Actually i realize that, when i remove custom method IsNullOrEmpty, I saw that SonarQube still didn’t find bug, too.
In this code sample it should generate bug S2259, right?
image

In addition, in the rule definiton,https://rules.sonarsource.com/csharp/RSPEC-2259?search=null, there is an explanation that I was not paying attention to. In the explanation ValidatedNotNullAttribute can be used for custom null check extension method.

Hi @ckonca,

You’re right about the FirstOrDefault example. It should trigger the rule, but it’s a know False Negative case that is already reported here.

The ValidatedNotNullAttribute is a good way of dealing with the False Positive from your first example.

1 Like