2

Why, in this powershell code, does the last statement resolve to true?

PS C:\> $s = [System.String]$null
PS C:\> $s.GetType()
IsPublic IsSerial Name                                     BaseType                                                                  
-------- -------- ----                                     --------                                                                  
True     True     String                                   System.Object 
PS C:\> $s -eq ""
True
Paul Raff
  • 306
  • 2
  • 9
  • 2
    `$s=[System.String][NullString]::Value` – user4003407 Apr 07 '16 at 07:02
  • Yes, or even `[System.String]$s=[System.String][NullString]::Value`. The meaning of the [variable `$null`](https://technet.microsoft.com/en-us/library/hh847768.aspx) is NULL ___or___ an empty value. Somewhat related to [Possible to pass null from Powershell to a .Net API that expects a string?](http://stackoverflow.com/questions/2002570/) – Jeppe Stig Nielsen Oct 17 '16 at 12:58
  • [related](https://stackoverflow.com/q/45720150/1404637) – alx9r Aug 27 '17 at 22:25

2 Answers2

1

PowerShell always converts null strings to empty string Check accepted answer here for details : Passing null to a mandatory parameter to a function

Community
  • 1
  • 1
smichaud
  • 326
  • 2
  • 12
  • Sure, but the details there don't go into the question of why. It would be nice to understand the motivation here. – Paul Raff Apr 07 '16 at 01:06
1

Basically so you never have to write string.IsNullOrEmpty() or get a null reference on a string in PowerShell. See Tony Hoare "Null References: The Billion Dollar Mistake".

Bruce Payette
  • 2,511
  • 10
  • 8