Is Nullable<T>.GetHashCode() a poor hash code function?
.net, c#, hashcode
Solution
Yes, you do have a point. It is always possible to write a better GetHashCode() implementation if you know up front what data you are going to store. Not a luxury that a library writer ever has available. But yes, if you have a lot of bool? that are either false or !HasValue then the default implementation is going to hurt. Same for enums and ints, zero is a common value.
Your argument is academic however, changing the implementation costs minus ten thousand points and you can't do it yourself. Best you can do is submit the suggestion, the proper channel is the user-voice site. Getting traction on this is going to be difficult, good luck.
Problem
The implementation of `Nullable<T>.GetHashCode()` is as follows: ``` public override int GetHashCode() { if (!this.HasValue) { return 0; } return this.value.GetHashCode(); } ``` If however the underlying value also generates a hash code of 0 (e.g. a bool set to false or an int32 set to 0), then we have two commonly occurring different object states with the same hash code. It seems to me that a better implementation would have been something like. ``` public override int GetHashCode() { if (!this.HasValue) { return 0xD523648A; // E.g. some arbitrary 32 bit int with a good mix of set and // unset bits (also probably a prime number). } return this.value.GetHashCode(); } ```