V3207. The 'not A or B' logical pattern may not work as expected. The 'not' pattern is matched only to the first expression from the 'or' pattern.
The analyzer has detected a code fragment that might contain a logical error. The pattern 'is not * or *' was detected in the conditional expression. The priority of the operator 'not' is higher than that of the operator 'or'. Due to this, the negation does not apply to the right side of the expression 'or'.
Look at the example:
private void ShowWordDetails(string key)
{
if (key is not "" or null)
{
PanelReferenceBox.Controls.Clear();
CurrentWord = Words.Find(x => x.Name == key);
....
}
}
The logic of the expression 'key is not "" or null' is broken. If 'key' is null, the result of the logical expression will be 'true' while 'false' was implied.
The operator 'not' is of higher priority than 'or'. The error occurs if a developer does not take it into account. In this pattern, the second subexpression of the operator 'or' is usually meaningless. For example, if 'key' is null in the expression 'key is not "" or null', the check for a non-empty string will result in 'true'. So, the second part of the expression will not affect the final result.
For correct operator precedence, one should use parentheses after the operator 'not'.
Fixed code:
private void ShowWordDetails(string key)
{
if (key is not ("" or null))
{
PanelReferenceBox.Controls.Clear();
CurrentWord = Words.Find(x => x.Name == key);
....
}
}
The code now works as expected. The condition checks that the string 'key' is not empty or 'null', instead of checking only for an empty string.
This diagnostic is classified as: