0

This question is related to the earlier asked question: Is it possible to reference another property in a constructor?

For my ConvertTo-Expression, I would like to keep track of object references so that I can check whether the property object has already been serialized. For this I am creating a hash table which uses the object's .GetHashCode() method (of non [ValueType] objects) as a Key.
This works for quiet some objects, but not for PSCustomObjects.

As an example, I want identify that the Parent property of the Child property references the same $Parent Object:

$Parent = [PSCustomObject]@{
    Name = "Parent"
}
$Child = [PSCustomObject]@{
    Name = "Child"
}
$Parent | Add-Member Child $Child
$Child | Add-Member Parent $Parent

Meaning that I expect that $Parent (, $Child.Parent) and $Parent.Child.Parent referencing the same object.

But the problem is that both $Parent.GetHashCode() and $Child.GetHashCode() already return the same Hashcode... even they are completely different from each other.

Obviously, as suggested in the description of How to: Test for Reference Equality (Identity) (C# Programming Guide), the correct way to check whether two objects have an equal reference is to use the Object.ReferenceEquals method:

[object]::ReferenceEquals($Parent, $Child)
False

Not only I would like to fix this in my ConvertTo-Expression cmdlet, I would also like to better understand this.
Why does the .GetHashCode() method return the same hashcode for different PSCustomObjects?
How can I create an index list of (unique) object references?
Or, is this simply not possible and should I just index all non [ValueType] objects properties and check the whole list for [Object.ReferenceEquals] which the current object property iteration?

iRon
  • 20,463
  • 10
  • 53
  • 79
  • I think psobject is just not hashable - all PSObject returning same hash (not just ones you mentioned). Even an empty one. From the other side the way you are doing it now is working. Like $parent and $parent.child.parent is the same thing – Mike Twc Jan 06 '19 at 18:43
  • Regarding hashcodes: Do not test for equality of hash codes to determine whether two objects are equal. (Unequal objects can have identical hash codes.) To test for equality, call the ReferenceEquals or Equals method. https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.7.2 – Sage Pourpre Jan 06 '19 at 20:35

0 Answers0