Can someone explain please why we have different behaviors when we are working with hash tables?
In fact, when the value is a simple type (integer, string…) or an object type, the behavior is different. When we are working with a simple type and we affect the value to a variable and update it; this will not update the hash table. But when we are working with an object type and we affect the value to a variable and update it; this will update the hash table.
It will be easier to understand with an example ^^.
Simple type:
$hash=@{
a=1
b=2
}
$variable = $hash['a']
$variable = 3
Result: $hash
Name Value
---- -----
a 1
b 2
Object type:
$hash=@{
a=New-Object PSObject -Property @{ obj=1 }
b=New-Object PSObject -Property @{ obj=2 }
}
$variable = $hash['a']
$variable.obj = 3
Result: $hash
Name Value
---- -----
a @{obj=3}
b @{obj=2}
It is because you use reference types and value types.
Object type:
$variable = $hash['a']
$variable.obj = 3
Here you retrieve the object reference and then access properties inside the object.
Simple type:
$variable = $hash['a']
$variable = 3
Here you copy the entire int to a new variable. So when the variable is updated, it is updated independently without influencing the hashtable.
To update the value of the hashtable you have to use $hash['a'] = 3
Check out difference between reference types and values types.
Edit: string is special because it is saved in the heap with a reference but it behaves like a value type. So it is copied when assigning to a new string and behaves like the int example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With