My Technical Notes

Friday, 18 December 2015

PowerShell: Passing null into optional string parameter in C# method

If we have a method with an optional argument:


public class MyClass
{
    public static void MyMethod(string arg1, string arg2 = null) 
    {
        
    }
}

And if we use this within our PowerShell script as so:


[MyClass]::MyMethod("Tahir", $null)

what will happen is that, for `arg2`, an empty string is passed across instead of `null`. To ensure that `null` is passed, we use `System.Management.Automation.Language.NullString.Value`:


[MyClass]::MyMethod("Tahir", [System.Management.Automation.Language.NullString]::Value)

No comments: