Possible false positive with c# list .FirstOrDefault where default value given

Since .NET 6, Linq added an overload to object.FirstOrDefault(lamda, object default) which allows the developer to offer a default object to read data from in the case that a match was not found for the lamda expression. An example is below:

object DefaultValue = new() {Value = “SomeValue”, Text = “Show Me”};
string MyValue = AllValues.FirstOrDefault(x => x.Value == “MyDesiredValue”, DefaultValue).Text;

In the above case, if no Value exists in the list of AllValues equal to “MyDesiredValue”, the resulting value for the Text property would be “Show Me”. There should never be a null in this case because we provided a non-null default.

SonarQube currently flags above code as a medium bug with the explanation that it could result in a null exception which is not possible. I believe this needs to be added to acceptable logic.

Hi,

Welcome to the community and thanks for this report!

Can you give your context for this? I.e. are you on SonarQube Cloud? SonarQube for IDE (flavor and version)? SonarQube self-managed (flavor and version)?

 
Thx,
Ann

Sure, sorry should have included this. This is in an analysis done by SonarQube Server in our Azdo Pipeline.

Hi,

Tell me about your SonarQube Server version, please. You can find it in the page footer if you’re not sure what it is.

 
Thx,
Ann

Enterprise version 2025.6.1 (117629)

1 Like

Hi,

Thanks! I’ve flagged this for the language experts.

 
Ann