Today I stumbled upon a strange bug, that seems to be a feature of .net framework. I had a method that performed some action upon a instance of a class, lets say Customer, based on the hash value of that record. Seems plain and simple, however my unit test exhibited a strange behavior – in some cases, although Customer record had been updated, it acted as if it was not changed.
Short investigation pointed to a field of type bool? (Nullable<bool>), that although its value was changed, returned the same hash code.
The problem is, that generic struct Nulllable<T> implements GetHashCode like this:
System.Boolean implements its the same method like this:
It boils down to the fact, that for both: null, and false, we get hash value of 0. That’s why, although Customer changed value of that field, from false to null, or he other way around, its hash value was still the same.
I consider this a bug, but on the other hand, returning -1 or 2 might save the day for Nullable<bool> but how about Nullable<Int32> ?