Powershell function argument default: Weirdness when it has a type constaint -


if have function parameter without type constraint:

> function ($s=$null) {if ($s -eq $null) {write-host "hi"} if ($s -eq "") {write-host "kk"}} > hi 

now if add type constraint it, $null interpreted differently:

> function ([string]$s=$null) {if ($s -eq $null) {write-host "hi"} if ($s -eq "") {write-host "kk"}} > kk 

i can't find doc explain this. it's not consistent.

in first example (function a), $s equivalent $null - it's null.

in second example (function b), because you're casting $s [string] object, it's empty string (equivalent [string]::empty), not $null.

you can check adding following each of functions:

if($s -eq [string]::empty){"empty!"}; 

only b print empty! - a evaluate $false

alternately, add this:

$s|get-member 

a throw error - same error you'll if run $null|get-member. b show $s string , list of members of class.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -