.NET natively knows UUID v4 aka Guid.NewGuid()
. But with preview 7 we get Version 7 of UUID's natively.
UUID v7
As GUID
is just another valid alternative name for UUID
, the new API is still inside System.Guid
:
var guid = Guid.CreateVersion7();
var guidWithTimestamp = Guid.CreateVersion7(DateTimeOffset.UtcNow);
The main advantage is the timestamp that is included in the UUID. Why? Let's have a look how UUID v7 is structured:
+------------------+---------------+----------------------+
| 48-bit timestamp | 12-bit random | 62-bit random |
+------------------+---------------+----------------------+
That gives 122 bits entropy with 6 bits for version and variant somewhere in the middle. The main advantage is that you can sort UUIDs by their creation time making them a better fit for databases than UUID v4.
Controlling the Timestamp
As the method expects a DateTimeOffset
a calling function can utilize a TimeProvider
to control UtcNow
:
var uuid = Guid.CreateVersion7(timeProvider.GetUtcNow());
timeProvider
can be retrieved via the DI container and be faked in testing scenarios.
Resources
- The GitHub Ticket: https://github.com/dotnet/runtime/issues/103658