CreateSequetialUuid – Answer

time to read 2 min | 248 words

I got a lot of interesting answers for the riddle, and here is my solution:

private static int sequentialUuidCounter;
public static Guid CreateSequentialUuid()
    var ticksAsBytes = BitConverter.GetBytes(DateTime.Now.Ticks);
    var increment = Interlocked.Increment(ref sequentialUuidCounter);
    var currentAsBytes = BitConverter.GetBytes(increment);
    var bytes = new byte[16];
    Array.Copy(ticksAsBytes, 0, bytes, 0, ticksAsBytes.Length);
    Array.Copy(currentAsBytes, 0, bytes, 12, currentAsBytes.Length);
    return bytes.TransfromToGuidWithProperSorting();

Basically, we use the current system ticks as the 1 – 8 bytes, and a counter incremented atomically on the 12 – 16 bytes. This ensures that even concurrent calls on the same tick will have a different value.

Note that this code explicitly allows the same guid on multiple machines. You can fix that by adding the MAC address as 9 – 12 bytes, which will make this globally unique, but this isn’t something that I actually need.

Additional challenge, why am I reversing the bytes?