Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object-Property assigned $null does not test true for $null

Tags:

powershell

I've started using PowerShell to get some things done and played with the variable $null in PowerShell.

I've encountered the problem that when I assign the variable $null to a variable defined in a class, the test returns false not true.

Example Code:

class test {
    [string]$test1
}

$test = [test]::new()

$test.test1 = $null

$null -eq $test2 # tests true

$null -eq $test.test1 # tests false

Now the test of the undefinded variable $test2 returns true as every undefined variable in PowerShell is assigned $null.

But if I test the property test1 of the object test which I assigned $null tests false for $null

Is it because in PowerShell $null is an object with the value $null and now the property of the object is not $null as it has the object $null assigned to it with an empty value?

I've read into the docs of Microsoft "Everything you wanted to know about $null", but it does not enlighten me.

If I do not initialize the variable, then it will test true for $null.

like image 537
toodumbtocode Avatar asked Aug 31 '25 20:08

toodumbtocode


1 Answers

$test.test1 is not $null, it's empty string (because you explicitely defined it's value to be [string]):

C:\> $test.test1.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Proof:

C:\> $test.test1 -eq ""
True
like image 59
Robert Dyjas Avatar answered Sep 03 '25 09:09

Robert Dyjas