4

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}
emekm
  • 742
  • 5
  • 9

1 Answers1

7

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.

Community
  • 1
  • 1
Fabian
  • 1,886
  • 14
  • 13
  • 1
    Very nice explanation. Pretty sure though that the value type-like behavior of strings stem from the fact that they're immutable in the runtime – Mathias R. Jessen Jul 24 '15 at 12:14