CSharp S2259 false positive for if statement with multiple conditions and null-conditional operator

We are getting ‘cp’ is null on at least one execution path. (S2259) for the below C# code snippet. This is identified for the second condition in the if statement, cp.value?.id.ToString(). This cannot be the case though because the first condition cp?.unit already checks for null and the “short-circuiting” AND operator is used, so the second condition gets never evaluated.

foreach (var cp in element.customProperties)
{
    if (cp?.unit == PropertyValueType.Feed && !string.IsNullOrWhiteSpace(cp.value?.id.ToString()))
    {
        // Do stuff
    }
}

We are using sonarcloud.io with the azure devops code analysis task (version 1.19.0)

1 Like