2

Is PowerShell's $null equivalent to .NET's null? I have a scenario, wherein I have to invoke a .NET method from PowerShell and pass null as method parameter. As of now, I am getting some assembly loading related error on method invocation. I am wondering if $null is the culprit. Also, please share if you know what is the correct way of invoking .NET method with null parameter from PowerShell.

Method signature:

void SetUp(IKernel kernel, Action<IBindingInSyntax<object>> obj)

Thanks

3
  • The method parameter is nullable ? Could you post the method's sign? Commented Jul 14, 2014 at 16:03
  • Yes. It's a reference type variable. Commented Jul 14, 2014 at 16:04
  • 5
    if you are in powershell version 2.0 and the param is string type try to declare the variable as [System.Management.Automation.Language.NullString]::Value Commented Jul 14, 2014 at 16:07

1 Answer 1

2

PowerShell converts it's $null to .NET's null just fine in function calls.

Proof by example.

Add-Type -TypeDefinition @"
public static class Foo
{
    public static bool IsNull(object o)
    {
        return o == null;
    }
}
"@ -Language CSharp

[Foo]::IsNull($null)

[Foo]::IsNull("string")

Output:

True
False

$null wraps a null reference to an object, and no wonder it just works, even though they are two different things.

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

3 Comments

This does not work if the type is something else other than object. In my case, it was a SecureString.
> Object Class -- Supports all classes in the .NET class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all .NET classes; it is the root of the type hierarchy. learn.microsoft.com/en-us/dotnet/api/system.object?view=net-5.0 @julealgon, I doubt SecureString is not an Object. Maybe you should ask a question and offer an example where this does not work.
SecureString is an object for sure, and I'm pretty sure it does not work there. I don't think asking another question is the way to go since it would be the same question as this one. I think this is the correct place to bring it up. Just replace object parameter on your method with SecureString (or anything other than object that is a reference type) and you should see the issue as well.

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.