0

using sonarqube to analyze my code and being told "'actor' is null on at least one execution path" for the following code

if (actor.ProducerAgreementIds != null && actor.ProducerAgreementIds.Count > 0)
   {

actor.ProducerAgreementIds is a List<string>.

isn't this statement already performing a null check? or should it instead be:

if (actor != null && (actor.ProducerAgreementIds != null && actor.ProducerAgreementIds.Count > 0))
    {

alternative would just using conditional access

if (actor?.ProducerAgreementIds != null && actor.ProducerAgreementIds.Count > 0)

be appropriate and not cause downstream issues?

thanks!

testing
  • 363
  • 1
  • 4
  • 10
  • 3
    Can you post your whole code? It's hard to make it out, when you're just posting snippets out-of-order. – canton7 Apr 25 '19 at 14:39
  • It might be a problem with multi-threading. This will do too btw: `if (actor?.ProducerAgreementIds?.Count > 0)`. – Patrick Hofman Apr 25 '19 at 14:42
  • A short way of writing this would be: if (prs?.Any() ?? false) – Metheny Apr 25 '19 at 14:44
  • I don't see the code which tests for `actor != null` in the code in your edit - please include that in your "whole code" – canton7 Apr 25 '19 at 14:55
  • Right, so we can't tell the relationship between the `actor != null` check, and the line on which the warning is raised. So we can't tell whether the warning is right or not. That means that we can't answer your question - there isn't enough information. Voting to close. I recommend coming up with a [mcve] which still reproduces the issue (remove some of those 508 lines, without affecting the warning). – canton7 Apr 25 '19 at 15:25

1 Answers1

1

With this validation it would be sufficient:

 if (actor?.ProducerAgreementIds?.Count > 0)
 {
 }
asd
  • 854
  • 7
  • 10