15

API:

namespace ClassLibrary1
{
    public class Class1
    {
        public static string Test(string input)
        {
            if (input == null)
                return "It's null";
            if (input == string.Empty)
                return "It's empty";
            else
                return "Non-empty string of length " + input.Length;
        }
    }
}

Script:

add-type -path C:\temp\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll
[classlibrary1.class1]::Test($null)
[classlibrary1.class1]::Test([object]$null)
[classlibrary1.class1]::Test([psobject]$null)
[classlibrary1.class1]::Test($dummyVar)
[classlibrary1.class1]::Test($profile.dummyProperty)

Output:

It's empty
It's empty
It's empty
It's empty
It's empty

What am I missing?

1
  • 1
    This is a great question and I am actually ashamed to say I didn't know about it as I've been a PowerShell whore for about two years and do a lot of PowerShell/.NET interop. Commented Jan 5, 2010 at 3:41

3 Answers 3

17

In order to pass a null value to an API call, use [NullString]::Value.

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

1 Comment

Absolutely! The NullString class was new in PowerShell 3 (from 2012). This is why the other answers could not know about [NullString]::Value.
7

According to this MS connect issue, this is a known problem. There are a couple workarounds posted there, too, like using reflection to pass the paramaters (which is clever, but kinda silly that it's required). Cheers!

1 Comment

Your link points to a login page. Could you please quote the workarounds posted there, for those of us, who do not have an MS connect account.
2

this is just how PowerShell behaves - it will always try to convert an object as long as it is convertible to the target type (in this case string). PowerShell will always convert null (the absence of a value) to String.Empty when casting into a string object.

Take a look at Bruce Payette's book "Windows PowerShell in Action", around page 142. Bruce is one of the architects behind PowerShell.

It's kinda one of those documented little gotchas of the scripting language, and we should definitely be aware of it.

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.