David Klempfner
David Klempfner

Reputation: 9868

How to check if a collection has a null reference

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

Answers (3)

David Klempfner
David Klempfner

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

TessellatingHeckler
TessellatingHeckler

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.

Example screenshot of testing an empty array

I suggest $null -eq $objectArray:

Example of using $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

user189198
user189198

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) {

}

enter image description here

Upvotes: 1

Related Questions