2

I'm new to Powershell and I'm confused about something, more specifically null and $null.

For example. let's say you have a function:

function myFunction([ref]$foo){ if($foo -ne $null){ ...do stuff } } 

And when you call this function, you do so like:

[ref]$foo = $null myFunction $foo 

If you execute the code above, the condition if($foo -ne $null) will return true.

However, if you call the function like:

$foo = $null myFunction $foo 

the condition if($foo -ne $null) will return false.

Why is this? Why is it that when you assign a ref variable $null, it isn't considered null when it is checked?

1
  • @jpmc26 Um, I can't remember.... Commented Jan 6, 2014 at 22:43

2 Answers 2

3

PowerShell seems to cast $null to some non-null value when you attempt to store it in a strongly typed variable. I believe this is the cause. Notice the following:

PS C:\> [ref]$foo = $null PS C:\> $foo Value ----- PS C:\> $foo.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False PSReference System.Object 

It appears that PowerShell is casting $null to a PSReference. I've seen similar behavior with strings:

PS C:\> [String]$str = $null PS C:\> $str -eq $null False PS C:\> $str -eq [String]::Empty True 

It confused the heck out of me when I had a [String] parameter on a function that I was defaulting to $null and my null check was never true.

Why would they do this? I wonder the same thing.

For strings, I ended up using [String]::IsNullOrEmpty (although there may be a more PowerShell-ish way). For PSReference, Value might suit your needs for the null check:

PS C:\> [ref]$foo = $null PS C:\> $foo.Value -eq $null True 

Note that we have just proven you won't run into a null reference error by accessing Value.

Sign up to request clarification or add additional context in comments.

Comments

1

Because $null is a special variable which is actually null, where as [ref]$foo is a strongly typed variable containing a reference to a location, which just so happens to be null.

So of course $ref -ne $null. $null is the null, $ref is a reference which could be null later.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.