11---
22description : Null Comparison
3- ms.date : 06/28/2023
3+ ms.date : 12/03/2024
44ms.topic : reference
55title : PossibleIncorrectComparisonWithNull
66---
@@ -18,8 +18,8 @@ There are multiple reasons why this occurs:
1818- ` $null ` is a scalar value. When the value on the left side of an operator is a scalar, comparison
1919 operators return a ** Boolean** value. When the value is a collection, the comparison operators
2020 return any matching values or an empty array if there are no matches in the collection.
21- - PowerShell performs type casting left to right, resulting in incorrect comparisons when ` $null ` is
22- cast to other scalar types.
21+ - PowerShell performs type casting on the right-hand operand , resulting in incorrect comparisons
22+ when ` $null ` is cast to other scalar types.
2323
2424The only way to reliably check if a value is ` $null ` is to place ` $null ` on the left side of the
2525operator so that a scalar comparison is performed.
@@ -55,10 +55,10 @@ function Test-CompareWithNull
5555## Try it Yourself
5656
5757``` powershell
58- # Both expressions below return 'false' because the comparison does not return an
59- # object and therefore the if statement always falls through:
58+ # This example returns 'false' because the comparison does not return any objects from the array
6059if (@() -eq $null) { 'true' } else { 'false' }
61- if (@() -ne $null) { 'true' } else { 'false' }
60+ # This example returns 'true' because the array is empty
61+ if ($null -ne @()) { 'true' } else { 'false' }
6262```
6363
6464This is how the comparison operator works by-design. But, as demonstrated, this can lead
0 commit comments