String, GetHashCode() produces the same code for different strings  
Author Message
Alex Galkin





PostPosted: Common Language Runtime, String, GetHashCode() produces the same code for different strings Top

string first = "MB7A175000";

string second = "MB7F185000";

if (first != second && first.GetHashCode() == second.GetHashCode())

{

Console.Out.WriteLine("Eh !");

}

else

{

Console.Out.WriteLine("OK");

}

So far I was sure different strings produce different hash code, but at the moment I'm confused.

I appreciate any help on the topic.




.NET Development14  
 
 
Dah_cn





PostPosted: Common Language Runtime, String, GetHashCode() produces the same code for different strings Top

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.

For more details here: http://msdn2.microsoft.com/en-us/library/system.object.gethashcode.aspx



 
 
Mark Benningfield





PostPosted: Common Language Runtime, String, GetHashCode() produces the same code for different strings Top

Hello All.

Alex:

As the article in Dah_cn's link tries to point out (in MS doc-ese ) not only is the GetHashCode() method one-way (as all hash algorithms are), but it is also one-sided. It only guarantees that the hash will be the same if the inputs are the same, not the converse.

If you need a hash that guarantees that the hash is the same for identical inputs, AND that the hash is unique for distinct inputs, then what you need is a cryptographic hash.

MDC (Message Detection Code) hash algorithms are used to ensure data integrity. An example would be the .NET MD5 implementation, MD5CryptoServiceProvider. Look here for more information (Alas, also in MS doc-ese).

HTH.