Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guid & GetHashCode uniqueness

Tags:

c#

.net

Given the following key:

int key = Guid.NewGuid().GetHashCode(); 

Is this key unique as the uniqueness of Guid?

like image 434
Ashraf Sayied-Ahmad Avatar asked Sep 06 '11 21:09

Ashraf Sayied-Ahmad


People also ask

What is GUID example?

Introduction to SQL Server GUID The numbers, or identifiers, help us reference things unambiguously. For example, we can identify John Doe by using his unique social security number 123-45-6789 . A globally unique identifier or GUID is a broader version of this type of ID numbers.

How do you create a GUID?

To Generate a GUID in Windows 10 with PowerShell, Type or copy-paste the following command: [guid]::NewGuid() . This will produce a new GUID in the output. Alternatively, you can run the command '{'+[guid]::NewGuid(). ToString()+'}' to get a new GUID in the traditional Registry format.

What is a GUID in data?

The GUID data type is a 16 byte binary data type. This data type is used for the global identification of objects, programs, records, and so on. The important property of a GUID is that each value is globally unique. The value is generated by an algorithm, developed by Microsoft, which assures this uniqueness.


1 Answers

The pigeonhole principle says no. A GUID has 16 bytes of information - 128 bits. An int has 32 bits of information. (EDIT: To clarify due to comments, the .NET GUID will allow these 128 bits to be set arbitrarily as far as I'm aware; randomly generated GUIDs follow a stricter pattern so there aren't 2128 different values which would be randomly generated. Still more than 232 though.)

There are 2128 possible GUIDs, and 232 possible hash codes - so you can't possibly have a different hash code for each GUID.

There's more than that though - GetHashCode() is never meant to represent uniqueness. If it can, then that's great - but it doesn't have to, even when there are enough int values available to do so.

It would be entirely valid for int.GetHashCode() to return (say) the value divided by two... so -1, 0 and 1 would all get a hash code of 0; 3 and 4 would get a hash code of 2 etc. It wouldn't be good (and it would be slower than just returning the value) - but it would be a valid implementation. It would satisfy all the constraints of GetHashCode - namely that if you call it on two equal values, it will return the same hash code.

In fact, returning a constant for all values is a valid implementation - although a pretty useless one, in that it renders the normally-fast lookup of a hash table into an O(N) operation.

like image 67
Jon Skeet Avatar answered Oct 16 '22 17:10

Jon Skeet