dotnet / dotnet/dotnet-api-docs
Documentation error: Object.GetHashCode regarding value types
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
The documentation for the Object type:
https://github.com/dotnet/dotnet-api-docs/blob/master/xml/System/Object.xml
...has a section that talks about `GetHashCode` and it makes the following claim:
> If value types do not override GetHashCode, the ValueType.GetHashCode method of the base class uses reflection to compute the hash code based on the values of the type's fields.
In the source code for `ValueType`, there are comments that suggest that this is factually incorrect:
/*=================================GetHashCode==================================
**Action: Our algorithm for returning the hashcode is a little bit complex. We look
** for the first non-static field and get its hashcode. If the type has no
** non-static fields, we return the hashcode of the type. We can't take the
** hashcode of a static member because if that member is of the same type as
** the original type, we'll end up in an infinite loop.
**Returns: The hashcode for the type.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
[MethodImpl(MethodImplOptions.InternalCall)]
public extern override int GetHashCode();
I can understand not wanting to document this behaviour exactly, because of course it would be undesirable for it to become contractual, rather than merely an implementation detail, but as far as I can tell, no aspect of this "uses reflection to compute the hash code based on the values of the type's fields". Saying that it uses reflection raises alarm bells with me with regard to performance; upon reading this, I immediately began to worry that not overriding `GetHashCode` on every single `struct` could result in every `GetHashCode()` call dynamically discovering all of the type's properties.
Perhaps a better wording for this might be:
> If value types do not override GetHashCode, the runtime supplies an implementation that computes the hash code based on the values of the type's fields.
Contributor guide
Assessment
This issue has not been assessed yet.