Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update PossibleIncorrectComparisonWithNull documentation with better example #1244

Merged
merged 3 commits into from
Jun 5, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions RuleDocumentation/PossibleIncorrectComparisonWithNull.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ function Test-CompareWithNull
## Try it Yourself

``` PowerShell
if (@() -eq $null) { 'true' } else { 'false' } # Returns false
if ($null -ne @()) { 'true' } else { 'false' } # Returns true
# Both expressions below return 'false' because the comparison does not return an object and therefore the if statement always falls through:
if (@() -eq $null) { 'true' } else { 'false' }
if (@() -ne $null) { 'true' }else { 'false' }
```
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.
``` PowerShell
PS> 1,2,3,1,2 -eq $null
PS> 1,2,3,1,2 -eq 1
1
1
PS> (1,2,3,1,2 -eq $null).count
0
PS> (1,2,$null,3,$null,1,2 -eq $null).count
2
```