Object.GetHashCode()
Gaurav Sharma here, I’m a developer with the Information Security Tools team.
Today I want to share something about FCL’s GetHashCode method. System.Object provides a virtual GetHashCode method so that an Int32 hash code can be obtained for any and all objects.
Below is a code snippet which takes a string and generates a hash code out of it. Code goes like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace HashCodeSample
{
class Program
{
static void Main(string[] args)
{
String message = "Hello from gaurav";
Console.WriteLine(String.Format("Hash is {0}", message.GetHashCode()));
Console.Read();
}
}
}
By definition, a hash is a value that summarizes a larger piece of data and can be used to verify that the data has not been modified since the hash was generated. So for a specific piece of data we will get identical hash every time we execute a specific hash function.
But strangely, this definition do not hold true for Object.GetHashCode method defined in FCL. I ran above code sample in VS 2003 and VS 2010 and got different outputs
Result with VS2003 [–
868154745]
Result with VS2010 [2020441803]
After digging deep into the MSDN for GetHashCode I got my answer-
The .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.
So, whenever we want to make use of hashing in our application we should always strive to use specific hashing algorithm types that are defined in FCL. Below is a class diagram showing available hash types.
Now my Tip of the Day for writing better code with Visual Studio:
Everyone uses Console.Writeline() method and visual studio provides a shortcut for typing this statement :).
Type cw and press TAB 2 times, you will get the statement. This feature is known as code snippets. Some of the snippets that I have in my mind right now are:
- Type ctor and 2 times TAB for CONSTRUCTOR
- Type switch and 2 times TAB for switch block. (if you have your VS open right now, just use this switch on a object of Enum type. You will be surprised how clever VS actually is)
- Type try and 2 times TAB for try catch block
There are lot of shortcuts available in VS that makes writing code fun.
Happy Coding!
Comments
- Anonymous
August 01, 2009
Thank You for sharing the code. Didn't worked the 1st time. Now its working. :)