What is the point of the null-condition operator in PowerShell?

263 Views Asked by At

PowerShell 7 recently moved out of the experimental stage the Null-conditional (?.) operator. In playing around with it a bit and reading the examples in the link above I think I understand how it works. In the following example, provided $a is not null and has a property called PropName it will return the value of $a.PropName or else return null.:

$a = @{ PropName = 100 }
${a}?.PropName # ==> 100

However, I don't understand why I would use the new null-conditional operator over accessing object properties using the dot (.). The below example renders the same both ways and does not throw or explicitly suppress any errors:

Dot

@{ PropName = 100 },
@{ PropNumber = 8675309 } | Foreach-Object {
  Write-Host ( $null -ne $_.PropName ? "PropName has a value of $($_.PropName)" : 'PropName is $null' )
}

# 1st iteration ==> PropName has a value of 100
# 2nd iteration ==> PropName is $null

Null-Conditional (note the subtle change)

@{ PropName = 100 },
@{ PropNumber = 8675309 } | Foreach-Object {
  Write-Host ( $null -ne ${_}?.PropName ? "PropName has a value of $(${_}?.PropName)" : 'PropName is $null' )
}

# 1st iteration ==> PropName has a value of 100
# 2nd iteration ==> PropName is $null

So, I understand when this is meant to be used, but PowerShell already had a solution for this with simpler syntax. I guess to put it bluntly, what is the point of this operator? I can't find much documentation on this operator aside from what I linked above, and I'm assuming there must be something I'm missing. There is a similar operator for arrays (?[]) to conditionally return an array element or $null if the index is out of bounds, but again, PowerShell already returns $null without error if you go out of bounds on an array and try accessing a property.

1

There are 1 best solutions below

0
codewario On

I realized the difference about 30 seconds after I submitted this. My testing above only tests Property members and does not take methods or strict-mode into account. But rather than delete the question, I think there is value in explaining this.

By default, Properties don't throw errors when they don't exist on an object, but you absolutely will get an InvalidOperation error if you try to execute a Method on a $null object. And strict-mode throws most of my dot-access example out entirely, as strict-mode will throw errors when you try to dot-access any member on a null-valued object (among other additional guardrails in place).

So in short, the ?. and ?[] operators are super-useful if you have objects with methods or if you are running PowerShell in strict-mode. Otherwise, in either of these cases you get to write more boilerplate code to do null checks first.