---
title: "UUID v7 in .NET 9"
description: ".NET natively knows UUID v4 aka `Guid.NewGuid()`. But with preview 7 we get Version 7 of UUID's natively. "
updated: 2024-07-08
tags: ["C#", ".NET", ".NET 9", "UUID", "GUID"]
canonical: "https://steven-giesel.com/blogPost/ea42a518-4d8b-4e08-8f73-e542bdd3b983/uuid-v7-in-net-9"
---

# UUID v7 in .NET 9

.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`:

```csharp
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:


```no-class
+------------------+---------------+----------------------+
| 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`](https://learn.microsoft.com/en-us/dotnet/api/system.timeprovider?view=net-8.0) to control `UtcNow`:

```csharp
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