Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell $null is not null any more when calling into C# code

In PowerShell one can define C# code and execute it. Passing in $null into the following simplest function shows that not null gets passed into the function

Add-Type -TypeDefinition @"
public static class foo
{
public static void fooo(string a)
{
    if(a!=null)
    {
        System.Console.WriteLine("Not Null. Is '" + a + "'");
    }
}
}
"@ -Language CSharp

Calling it as follows leads to the output Not Null. Is ''. This shows that $null was not null in C#. Methods like 'IsNullOrEmpty' or 'IsNullOrWhiteSpace' return true, so PowerShell must have implicitly converted the $null into a string.

[foo]::fooo($Null)

Any ideas why this is happening and if there is a better fix apart from rather calling String.IsNullOrEnpty in C#? NB: This happens irrespective of the C# language specified 'Add_Type'. I'm using PowerShell V5.

like image 926
bergmeister Avatar asked Aug 15 '16 15:08

bergmeister


People also ask

How do I use $null in PowerShell?

$null is an automatic variable in PowerShell used to represent NULL. You can assign it to variables, use it in comparisons and use it as a place holder for NULL in a collection. PowerShell treats $null as an object with a value of NULL. This is different than what you may expect if you come from another language.


1 Answers

Evidently the solution is "don't pass $null to a [String] parameter if you want a $null [String]". There is a special [NullString] class that should be used instead.

PS > [foo]::fooo($Null)
Not Null. Is ''
PS > [foo]::fooo([NullString]::Value)
PS >

I can't find any mentions of the need to use [NullString] in the PowerShell documentation, nor does the source code for the NullString class include any comments explaining its purpose.

like image 118
Lance U. Matthews Avatar answered Sep 28 '22 04:09

Lance U. Matthews