PowerShell / PowerShell/PowerShell

.GetHashCode() should not report the same value for all instances of [pscustomobject]

Open
#15,806 3 comments 4 reactions 1 assignee View on GitHub

@JamesWTruher is already working on this.

Since Oct 27, 2021.

KeepOpen WG-Engine
Dominant language
C#
Stars
55.5k
Forks
8.5k
Avg merge
1d 2h
Merged PRs (30d)
88

Description

Prerequisites
Steps to reproduce

[pscustomobject] is a reference type without overridden equality-comparison behavior, so testing for equality performs reference equality, i.e. the test only succeeds if to values point to the very same instance.

Such types usually use the default (inherited) .GetHashCode() implementation, which for reference types means a value that is derived from the instance's identity.

Unexpectedly, all [pscustomobject] instances return the same from their .GetHashCode() method, which makes [pscustomobject] unsuitable as a hashtable key, for instance.

Expected behavior
PS> ([pscustomobject] @{ foo=1 }).GetHashCode() -eq ([pscustomobject] @{ foo=1 }).GetHashCode()
False # Two distinct [pscustomobject] instances that compare unequally should have distinct hash codes.
Actual behavior

The above returns $true, even though [pscustomobject] @{ foo=1 } -eq [pscustomobject] @{ foo=1 } returns $false (due to reference equality being tested).

Error details

No response

Environment data
PowerShell Core 7.2.0-preview.7
Visuals

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.