JohnB
JohnB

Reputation: 4379

How do I create a guanranteed unique hash across a collection of unique strings in .Net?

I am looking for advice for either finding or creating a hash algorithm to be used in .Net C#.

I have a collection of columns from a DB. The combination of columns across the table are guaranteed to produce unique strings.

Consider:

String Column1 = "StringA";
String Column2 = "StringB";
String Column3 = "StringC";

I concatenate the columns into a single string:

String ColumnKey = Column1 + Column2 + Column3;

Currently I'm using the built in .Net C# hash function from the string class.

int hashKey = ColumnKey.GetHashCode();

After doing some reading, it's my understanding that (although the probability is quite low) this algorithm does not guarantee uniqueness. It is also my understanding that this function could produce different results for the same string across different versions of the .Net Framework.

I am looking for another hash algorithm to use that would guarantee uniqueness and produce consistent results across different versions of .Net.

Can someone help get me started in the right direction?

Upvotes: 1

Views: 6352

Answers (2)

Yair Halberstadt
Yair Halberstadt

Reputation: 6891

It's impossible. There are 2^32 different values for an int, and a string just a few characters long has more possible values than this. As a result no hashing algorithm can guarantee a unique value for each string.

See the PigeonHole Principle. https://en.wikipedia.org/wiki/Pigeonhole_principle.

If you want a guaranteed hash for every version of .Net, implement the hash yourself. A fast hash function for string in C# gives a few examples. I would put it in an extension method for string.

Upvotes: 4

BradleyDotNET
BradleyDotNET

Reputation: 61379

There is no such thing as a "guaranteed unique hash". Hash's have a size (in .NET 32-bit) so there are only 4-billionish possible hashes. Have more strings than that and you have to have a collision.

So what you are asking for is not possible.

Upvotes: 1

Related Questions