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?