Carol
Carol

Reputation: 271

What is the GetHashCode method for?

What is the GetHashCode method of a string object?

Is this the same as when you compute the hashcode of something? But GetHashCode returns int, shouldn't it return a byte array?

thanks!

Upvotes: 0

Views: 150

Answers (2)

Jon
Jon

Reputation: 437376

What it should return depends on the size of the hash. If the hash can serve its purpose with the relatively small size of 32 bits, then returning it as an int makes practical sense. This was also (and I suppose it still is) common when calculating the crc32 checksum, which as its name implies is 32 bits long.

The purpose of the hash in .NET is explained in the documentation as other answers mention. In short, the hash is used in .NET to:

  • Coarsely compare two objects for equality (you know they are not equal if the hashes do not match)
  • Disperse objects across the length of a hashtable when they are put into one

Upvotes: 1

Casey Wilkins
Casey Wilkins

Reputation: 2595

This will tell you what a hashcode is for:

http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

A hash code is a numeric value that is used to identify an object during equality testing. It can also serve as an index for an object in a collection.

Note that the default implementation of Object.GetHashCode returns an integer. A hash doesn't necessarily have to return a byte array to be a hash.

And this will tell you about the string hashcode:

http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx

Upvotes: 0

Related Questions