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}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.