Skip to content

PSPossibleIncorrectComparisonWithNull rule is questionable #200

Closed
@KirkMunro

Description

@KirkMunro

I disagree with the use of the PSPossibleIncorrectComparisonWithNull rule. Script authors need to understand how comparisons against $null work when it comes to collections, however there are scenarios where you may want to use a comparison operator with a collection against $null. For example, if you have some null values in a collection, you can remove them like this:

$d = @('a',$null,'b',$null,'c') -ne $null
$d.Count # returns 3

In that scenario, you don't want to $null on the left hand side of the -ne operator, because that is a totally different function.

Further, unlike other languages, it is not possible to unintentionally cause assignment when using the PowerShell comparison operators. For example, in C++, I compare values using ==. But if I mistakenly type a single '=', then I'm performing an assignment. In PowerShell, you can't do anything to -eq/-ne to make them do assignment.

The only potential risk with $null on the right hand side is when the item on the left hand side is an array. If it is not, there is no need to make the change. Why then would PSPossibleIncorrectComparisonWithNull raise what is essentially a compiler warning for values that are not arrays?

If this rule truly must stick around, then I would like it changed such that it only generates a warning when it either does not know the type of the object on the left hand side of the equality comparison operator or when the type of the object on the left hand side is a collection.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions