0

If I have a function parameter WITHOUT the type constraint:

> function a ($s=$null) {if ($s -eq $null) {Write-Host "HI"} if ($s -eq "") {Write-Host "KK"}}
> a
HI

Now if I add the type constraint to it, the $null is interpreted differently:

> function a ([string]$s=$null) {if ($s -eq $null) {Write-Host "HI"} if ($s -eq "") {Write-Host "KK"}}
> a
KK

I can't find doc that explain this. It's also not consistent.

3
  • What is the question? Commented May 2, 2013 at 19:16
  • The OP is looking for an explanation of the difference in the behavior of the two functions when the parameter is coerced into being a string in one version, but not in the other. I don't understand whats "not consistent" here, but the behavior demonstrated here can be explained. Commented May 2, 2013 at 19:30
  • 1
    I guess it's not consistent with C#, since I don't think casting or assigning null to a string will result in string.Empty in C#. But then there's no requirement that PowerShell be consistent with C# as they're different languages. Similarly, F# also has different behaviors than C#, and it's by design. Commented May 2, 2013 at 21:15

1 Answer 1

2

In your first example (function a), $s is equivalent to $null - it's truly null.

In your second example (function b), because you're casting $s to a [string] object, it's actually an empty String (equivalent to [String]::Empty), not $null.

You can check this by adding the following to each of your functions:

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

Only b will print empty! - a will evaluate this to $false

Alternately, add this:

$s|get-member

a will actually throw an error - the same error you'll get if you run $null|get-member. b will show you that $s is a string and list all of the members of that class.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.