Should GetHashCode return a nonnegative value

  • Thread starter Thread starter Niko Korhonen
  • Start date Start date
N

Niko Korhonen

The return type for the .NET framework System.Object's method
GetHashCode is a signed integer. However, I've noticed that especially
when doing some XOR magic, the hash code tends to be a large negative
number.

My question is that should user-defined GetHashCode method always return
a nonnegative number? I think that the most common use for hash codes is
something like this:

# hashTable[obj.GetHashCode() % hashTable.Length] = obj;

But when GetHashCode returns a negative number, the result of the modulo
calculation is negative and therefore the code throws array index exception.
 
Niko Korhonen said:
The return type for the .NET framework System.Object's method
GetHashCode is a signed integer. However, I've noticed that especially
when doing some XOR magic, the hash code tends to be a large negative
number.

My question is that should user-defined GetHashCode method always return
a nonnegative number? I think that the most common use for hash codes is
something like this:

# hashTable[obj.GetHashCode() % hashTable.Length] = obj;

But when GetHashCode returns a negative number, the result of the modulo
calculation is negative and therefore the code throws array index
exception.

The system Hashtable casts the int to a uint before performing the module,
so any value (positive, negative or zero) is a valid hashcode.

Stu
 
Back
Top