I am stumped by a seemingly simple problem. I have two objects that I am comparing with a !=.
When I run the application, a != b is true.
When I put a breakpoint and do a Watch, a.GetHashCode() == b.GetHashCode() is true.
These two (reference type) objects are defined in a different assembly, but I cannot find an override to the != method (although GetHashCode is overridden). Is there another explanation for this? Could it be possible that a GetHashCode for two objects could be the same, but a not-overriden != would return true?
Thanks.
When two objects that are different return the same code it is called a “collision”. With only ~4 billion possible integer values, and more than 4 billion possible values of [your class name here] some collisions are inevitable. This is why a hash based structure (i.e.
Dictionary) can’t rely entirely onGetHashCode, it also needs a sensibleEqualsimplementation to be effective. TheEqualsmethod is what is used to resolve these collisions.Of course it’s also possible that the creator of the class overwrite either
GetHashCodeorEqualsand in some way made a mistake that in some way violated the “contract” for generating hash codes. Here is one list of guidelines to keep in mind when creating yourGetHashCodemethods. Remember that there is a fairly small set of things that you have to do, and another set of things that can be done to make it work efficiently.return 0;is actually a perfectly acceptableGetHashCodeimplementation. It conforms with all of the rules, it just has a 100% chance of causing collisions, so it will be extraordinarily inefficient and you shouldn’t ever actually do that.