Generate a UUID in C#
Generate, format, parse, and validate UUIDs and GUIDs in C# and .NET with native Guid methods and .NET 9 UUIDv7 support.
In C# and the .NET runtime, UUIDs are represented by the System.Guid value type (struct). While historically Microsoft used the term GUID (Globally Unique Identifier), .NET's Guid struct implements RFC 4122/9562 standard 128-bit UUIDs and is binary-compatible with UUIDs generated on Linux, macOS, and web platforms.
Quick Start#
Generate a standard random UUID v4 in C# using Guid.NewGuid():
.NET 9 UUIDv7 Support#
Starting with .NET 9, Microsoft introduced native support for time-ordered UUIDv7 via Guid.CreateVersion7():
UUIDv7 provides optimal performance for SQL Server, PostgreSQL, and SQLite primary keys by drastically reducing B-tree page splits.
Formatting Formats & Specifiers#
The Guid.ToString(string format) method supports standardized format specifiers:
Parsing and Validation#
Use Guid.TryParse for fast, allocation-free validation that handles all standard string formats without throwing exceptions:
Converting to Byte Arrays & Endianness Caution#
When converting a Guid to bytes in .NET, be aware of Microsoft's historical mixed-endian internal byte layout:
Best Practices#
- Use
Guid.TryParseinstead ofGuid.Parse: Avoids costly exception handling when validating user inputs. - Check for
Guid.Empty: Ensure required foreign keys or entity IDs are not default uninitialized structs. - Use
Guid.CreateVersion7()in .NET 9+: Replace sequential GUID generators (such asRT.ComborNEWSEQUENTIALID()) with standard UUIDv7.