Code guide

Generate UUIDs (GUIDs) in C#

Generate GUIDs in C# with Guid.NewGuid, parse and validate them, and create UUID v7 on .NET 9 and later.

In .NET, UUIDs are represented by the Guid type. Guid.NewGuid() covers version 4, and .NET 9 added native UUID v7 generation.

Key takeaways

  • Guid.NewGuid() creates a version 4 identifier.
  • Guid.TryParse validates input without throwing.
  • .NET 9 adds Guid.CreateVersion7() for time-ordered GUIDs.

For implementation context, continue with GUID Generator, UUID vs GUID, and UUID v7. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.

Generate and validate a GUID

NewGuid returns a random version 4 value. Use TryParse for safe validation of user input.

Guid id = Guid.NewGuid();          // version 4
string text = id.ToString();

if (Guid.TryParse(input, out Guid parsed))
{
    // parsed now holds a valid GUID
}

UUID v7 on modern .NET

.NET 9 introduced UUID v7 generation. Its timestamp-first layout can improve index locality when the database compares UUIDs in that order. SQL Server uniqueidentifier has its own comparison order, so benchmark that engine rather than assuming the same result.

// .NET 9 and later
Guid v7 = Guid.CreateVersion7();

Choose a GUID format explicitly

Use D for the 36-character hyphenated form, N for 32 hexadecimal digits, or B for braces. These are different representations of the same Guid; formatting cannot turn v4 into v7.

TryParse accepts several formats. Use TryParseExact when an API requires one representation, and compare with Guid.Empty if all-zero IDs are forbidden. At binary boundaries, confirm the byte order expected by both systems before using ToByteArray().

Guid id = Guid.NewGuid();
Console.WriteLine(id.ToString("D")); // hyphenated
Console.WriteLine(id.ToString("N")); // no hyphens

if (!Guid.TryParseExact(input, "D", out Guid parsed) || parsed == Guid.Empty)
{
    throw new ArgumentException("Expected a non-empty hyphenated GUID");
}

FAQ

Generate UUIDs (GUIDs) in C# questions

Are GUID and UUID the same in C#?

Yes. .NET calls the 128-bit identifier a Guid, which is the same format as a UUID.

How do I generate UUID v7 in C#?

On .NET 9 and later, use Guid.CreateVersion7(). On older runtimes, use a library.

Should I use Guid.Parse or Guid.TryParse?

Use TryParse for user input so invalid values return false instead of throwing.

Primary references

Standards and technical sources

The implementation and guidance on this page are checked against these standards and platform documentation sources.

Generate UUID / GUID in C# - .NET Examples