Generate UUID v4 and v7 in C#

In .NET, a UUID is represented by the System.Guid value type. Choose Guid.NewGuid() for random v4 IDs or, on .NET 9 and later, Guid.CreateVersion7() for IDs with a timestamp prefix.

UUID v4: Guid.NewGuid()

using System;

Guid id = Guid.NewGuid(); // UUID v4
Console.WriteLine(id.ToString("D"));

This API is available in .NET Framework and modern .NET. The value has no embedded creation timestamp. See Microsoft’s NewGuid reference, or generate a UUID v4 here to try the format.

UUID v7: .NET 9 or later

.NET 9 introduced UUID v7 generation. Target net9.0 or later in your project; the method is not available in .NET 8 or .NET Framework. Put this complete example in a console project’s Program.cs and run dotnet run:

using System;

Guid id = Guid.CreateVersion7(); // .NET 9 or later
Console.WriteLine(id.ToString("D")); // hyphenated
Console.WriteLine(id.ToString("N")); // no hyphens
Console.WriteLine(id.ToString("B")); // braces
Console.WriteLine(id.ToString("D").ToUpperInvariant());

D, N, and B format the same value with hyphens, without hyphens, or with braces. They do not change its version. See Guid.ToString formats. For fixtures without writing a program, the bulk UUID generator offers these representations and structured exports.

Generate v7 for a specific timestamp

using System;

DateTimeOffset timestamp = new(2022, 2, 22, 19, 22, 22, TimeSpan.Zero);
Guid id = Guid.CreateVersion7(timestamp);
Console.WriteLine(id); // starts with 017f22e2-79b0-7
// The remaining random fields change on each call.

The DateTimeOffset overload requires an instant at or after the Unix epoch. A fixed timestamp still produces random IDs, so this is not a deterministic fixture generator. The parameterless overload uses the current UTC time.

Paste the generated value into the UUID v7 timestamp converter to check the embedded milliseconds and UTC time, or use the UUID decoder to inspect its version and variant.

Using a Guid as a database key

Keep a unique constraint and a separate field for the event time your application needs. The random suffix means .NET v7 IDs created in the same millisecond are not guaranteed to sort in generation order. Database comparison rules and arrival order also matter; measure your workload before expecting an indexing speedup.

For a PostgreSQL uuid column, send the Guid through your database driver’s parameter binding. The PostgreSQL v7 guide covers generating on the database side and supporting older servers. Do not use an ID as a password or as a replacement for authorization.