Reputation: 9868
I just discovered that when you apply bool operators on a collection, it acts as a filter on that collection.
So the following will return all elements that are not null:
$objectArray = @('a','b','c','d')
$objectArray -ne $null
But how can I check if the collection's reference is null?
Upvotes: 2
Views: 226
Reputation: 9868
The following tells you if the reference is null:
[Object]::ReferenceEquals($objectArray, $null)
Testing if the variable is $true
or $false
does not always work because an empty collection will cast to false:
$objectArray = @()
if (!$objectArray) {
'The array is not actually null'
}
Upvotes: 0
Reputation: 29003
Trevor Sullivan's if ()
test forces the $objectArray
to cast to a boolean.
[bool]$null #is $false
[bool]@(1,2,3) # is $true , so it looks good.
But empty arrays mislead it:
[bool]@() # is $false , so it's not an accurate test.
I suggest $null -eq $objectArray
:
NB. It really opens the question of why you want to know if it's $null, specifically. Trevor's answer is typical and good enough for any common use.
NB. My answer includes an uncommon, but useful suggestion - when you have a literal value for one side of a comparison, put it on the left if you can.
0 -lt $counter
$null -eq $thing
"text" -eq $variable
4 -in $collection
It's less common, so looks less familiar, but it's more resilient against PowerShell implicit casting doing something you don't expect.
Upvotes: 2
Reputation:
All you have to do is test the variable for $true
or $false
. If it's $false
, then it's a null reference, otherwise the opposite is true.
if (!$objectArray) {
}
Upvotes: 1