Nullable<bool> GetHashCode() – bug or a feature?

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:

public override bool GetHashCode()

{

    if(this.HasValue)

        return Value.GetHashCode();

    return 0;

}

System.Boolean implements its the same method like this:

public override bool GetHashCode()

{

    if(this)

        return 1;

    return 0;

}

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> ?

Technorati Tags: , , ,

Comments

egony says:

MSDN Libray says:

If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.