Skip to content

Commit 1901be3

Browse files
authored
Add example from Jim
1 parent 4f26261 commit 1901be3

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

Diff for: RuleDocumentation/PossibleIncorrectComparisonWithNull.md

+12-1
Original file line numberDiff line numberDiff line change
@@ -43,5 +43,16 @@ function Test-CompareWithNull
4343
``` PowerShell
4444
# Both expressions below return 'false' because the comparison does not return an object and therefore the if statement always falls through:
4545
if (@() -eq $null) { 'true' } else { 'false' }
46-
if (@() -ne $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
4758
```

0 commit comments

Comments
 (0)