Object.GetHashCode()
Object.GetHashCode () gives us the hash code for an object. But as the documentation says, we should not use it for uniqueness. Because every object will give a hashcode and it will be same till the object lives. There can be cases where two different objects have same hashcode. This is very much possible. This is because Object.GetHashCode () returns an integer which contains a 32 bit value. And if there are more than 2^32 objects living in memory, then the hash code tends to repeat thought they are different objects if checked using Object.Equals() method. I’m not saying that only after 2^32 objects in memory, the hash code will repeat, but this is one case where the hash code can repeat. Also hashcode is an integer and it can have at the most 2^32 values. So, the hashcode can repeat. I tried to make the hashcode repeat on my system. Here is the code for it.
Hashtable hsTable = new Hashtable ();
while (true)
{
object obj1 = new object ();
int _hashCode = obj1.GetHashCode ();
if (hsTable.ContainsKey(_hashCode))
{
Debug.Write("Duplicate Hashcode: " + _hashCode);
break;
}
hsTable.Add(_hashCode, null);
}
Result:
Duplicate Hashcode: 65193
So, we do get same hashcode for different objects. MSDN says: “The default implementation of GetHashCode does not guarantee uniqueness or consistency; therefore, it must not be used as a unique object identifier for hashing purposes”. Hence proved :)
There are more things to talk about Object.GetHashCode(), but I’m still working on them!
0 Comments:
Post a Comment
<< Home