I saw this code recently in a struct
and I was wondering what base.GetHashCode
actually does.
public override int GetHashCode()
{
var hashCode = -592410294;
hashCode = hashCode * -1521134295 + base.GetHashCode();
hashCode = hashCode * -1521134295 + m_Value.GetHashCode();
return hashCode;
}
The base class of a struct is the
ValueType
class, and the source code is online. They helpfully left a comment that describes how it works:ValueType.GetHashCode:
The coreclr repo has this comment:
However, the code isn't there, and it looks like that's not quite what happens. Sample:
Output on my box:
Changing the value of
y
doesn't appear to change the hash code offoo
.However, if we make the fields
int
values instead, then more than the first field affects the output.In short: this is complex, and you probably shouldn't depend on it remaining the same across multiple versions of the runtime. Unless you're really, really confident that you don't need to use your custom struct as a key in a hash-based dictionary/set, I'd strongly recommend overriding
GetHashCode
andEquals
(and implementingIEquatable<T>
to avoid boxing).