Friday, 29 August 2014

PowerShell strings can't be $null (step in NullString)

I'd assumed that $[string]$arg = $null would set $arg to $null if no argument was specified ... but we all know what assumption makes :(

Summary

[string]$x = $null
$x -eq $null  # False !!!

[NullString]$x = $null
$x -eq $null  # True



Simple test


function Test {
  param(
    [string]$arg = $null
  )
 
  if($arg -eq $null) {
    Write-Host "Is $null"
  } elseif ($arg -eq [string]::Empty) {
    Write-Host "Is string.Empty!"
  } else {
    Write-Host ("Arg set to '{0}'" -f $arg)
  }
  
  if([string]::IsNullOrWhiteSpace($arg)) {
    Write-Host "IsNullOrWhiteSpace"
  }
}

cls

Write-Host 'Arg: No arg'
Test
Write-Host

Write-Host 'Arg: $null'
Test $null
Write-Host

Write-Host 'Arg: Something'
Test "Something"
Write-Host

Write-Host 'Arg: ""'
Test ""
Write-Host

PowerShell Console


Arg: No arg
Is string.Empty!
IsNullOrWhiteSpace

Arg: $null
Is string.Empty!
IsNullOrWhiteSpace

Arg: Something
Arg set to 'Something'

Arg: ""
Is string.Empty!
IsNullOrWhiteSpace

Got me thinking


It appears that strings can't be $null.
At least it's consistent if completely bonkers :(



[string]$x = $null
$x -eq $null  # False !!!

NullString to the 'rescue'


[NullString]$x = $null  $x -eq $null  # True

No comments: