Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell hashtable manipulation

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}
like image 877
emekm Avatar asked Mar 15 '23 07:03

emekm


1 Answers

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.

like image 109
Fabian Avatar answered Mar 23 '23 10:03

Fabian