How to generate absolutely unique GUID's?

No, there isn't any way to generate absolutely unique GUIDs. There are only 3.40282367 × 1038 possible GUIDs so as galaxies collide so will these identifiers. Even for a single application, it depends on how many GUIDs the application has. Unless your app is bigger than all of Google's indexers combined, you don't need to lose sleep over this. Just use Guid.NewGuid().


Sure. A GUID is just a 128-bit value. So use a 128-bit integer (e.g. represented by two ulong values) and increment it. When you've reached the maximum value for the 128-bit integer type, you've generated all possible GUIDs. For example:

public IEnumerable<Guid> GetAllGuids()
{
    unchecked
    {
        byte[] buffer = new byte[16];
        ulong x = 0UL;
        do
        {
           byte[] high = BitConverter.GetBytes(x);
           Array.Copy(high, 0, buffer, 0, 8);
           ulong y = 0UL;
           do
           {
               y++;
               byte[] low = BitConverter.GetBytes(y);
               Array.Copy(low, 0, buffer, 8, 8);
               yield return new Guid(buffer);
           } while (y != 0UL);
           x++;
        } while (x != 0UL);
    }
}

Notes:

  • This is definitely not as efficient as it might be.
  • Iterating over all possible ulong values is a pain - I don't like using do...while...
  • As noted in comments, this will produce values which are not valid UUIDs

Of course, this is in no way random...

In practice, as others have mentioned, the chances of collisions from Guid.NewGuid are incredibly small.


Not 100%. But if your GUID generator works well, the collision probability is very very small. This can practically count as 0.

A randomly generated (kind 4) guid has about 120 random bits. From the birthday problem you can see that collisions get likely once you generate about 2^60 or 10^18 GUIDs, which is a damn lot.

So simply using Guid.NewGuid() should be good enough.


Your proposed solution isn't a good idea IMO:

  • It can take a lot of memory if you have a lot of GUIDs
  • Since you need to know all GUIDs locally, there is no reason to use a GUID in the first place. A simple integer counter would do the job just as well.
  • Random GUID collisions are less likely than faulty hardware corrupting your data structure.

Your code itself looks correct to me. i.e. if you register all GUIDs and your hardware works perfectly, and the software has no other bugs you are guaranteed no collisions.

And of course it's not threadsafe either, which is unexpected for a static method.

Tags:

C#