Skip to content

Commit c23bf1c

Browse files
authored
Merge pull request #1244 from PowerShell/bergmeister-docs-1
Update PossibleIncorrectComparisonWithNull documentation with better example
2 parents a7dbee1 + 1901be3 commit c23bf1c

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

RuleDocumentation/PossibleIncorrectComparisonWithNull.md

+14-2
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,18 @@ function Test-CompareWithNull
4141
## Try it Yourself
4242

4343
``` PowerShell
44-
if (@() -eq $null) { 'true' } else { 'false' } # Returns false
45-
if ($null -ne @()) { 'true' } else { 'false' } # Returns true
44+
# Both expressions below return 'false' because the comparison does not return an object and therefore the if statement always falls through:
45+
if (@() -eq $null) { 'true' } else { 'false' }
46+
if (@() -ne $null) { 'true' }else { 'false' }
47+
```
48+
This is just the way how the comparison operator works (by design) but as demonstrated this can lead to unintuitive behaviour, especially when the intent is just a null check. The following example demonstrated the designed behaviour of the comparison operator, whereby for each element in the collection, the comparison with the right hand side is done, and where true, that element in the collection is returned.
49+
``` PowerShell
50+
PS> 1,2,3,1,2 -eq $null
51+
PS> 1,2,3,1,2 -eq 1
52+
1
53+
1
54+
PS> (1,2,3,1,2 -eq $null).count
55+
0
56+
PS> (1,2,$null,3,$null,1,2 -eq $null).count
57+
2
4658
```

0 commit comments

Comments
 (0)