Update PossibleIncorrectComparisonWithNull.md#733
Conversation
This is technically more accurate. PowerShell doesn't check for a $null in the array as was previously indicated.
|
|
||
| There are a number of reasons why this should occur: | ||
| * When there is an array on the left side of a null equality comparison, PowerShell will check for a `$null` IN the array rather than if the array is null. | ||
| * When there is an array on the left side of a null equality comparison, PowerShell will create a new array containing one `$null` item for each `$null` in the original array rather than check if the array is null. |
There was a problem hiding this comment.
Can you please provide a reference for the statement create a new array containing one $null item for each $null in the original array rather than check if the array is null?
There was a problem hiding this comment.
I think Get-Help about_Comparison_Operators explains this much better:
"When the input to an operator is a scalar value, comparison operators return a Boolean value. When the input is a collection of values, the comparison operators return any matching values. If there are no matches in a collection, comparison operators do not return anything."
Effectively by putting $null on the left hand side, you enforce PowerShell to use the scalar equality comparer, which guarantees a boolean return value (because if $null was on the right hand side, it can return nothing, which can lead e.g. to cases where e.g. if($obj -eq $null) always goes through the if path). I think it would be better to give examples where stuff can go wrong like e.g.:
if( (@() -eq $null) -and (@() -ne $null) ){"This is logically impossible but correct in PowerShell"}
There was a problem hiding this comment.
If there are no matches in a collection, comparison operators do not return anything.
Even that's not completely accurate. The comparison operator will return an empty array:
$result = (1..5) -eq $null
$result.GetType().FullName
# System.Object[]
$result.Count
# 0It's a weird gotcha topic, for sure!
Revised description based on comments.
|
I had completely forgotten about this PR. @dlwyatt's comment drew my attention to it again because I received a notification. I reviewed all comments and updated the text to a slightly corrected version of what is found elsewhere in the help documentation (slightly corrected for the inaccuracy that was identified in that documentation). |
|
Thanks @KirkMunro |
This is technically more accurate. PowerShell doesn't check for a $null in the array as was previously indicated.