ZetCode

C# Guid

last modified November 15, 2026

This article shows how to work with the Guid type in C#. We cover creating random and time-ordered GUIDs, formatting, parsing, equality, the byte layout, and name-based GUIDs.

A GUID (globally unique identifier), also known as a UUID (universally unique identifier), is a 128-bit value used to identify objects without a central authority. GUIDs are used as database keys, file names, correlation IDs in logs, and COM interface identifiers. The standard text form consists of 32 hexadecimal digits in five groups separated by hyphens, for example 0f8fad5b-d9cb-469f-a165-70867728950e.

The UUID format is defined in RFC 9562. A UUID contains a version number in the first digit of the third group and a variant in the first digit of the fourth group. Version 4 GUIDs are random; version 7 GUIDs start with a timestamp, so they sort by creation time. In .NET, the System.Guid struct represents a GUID. It is a value type of 16 bytes.

Creating random GUIDs

The Guid.NewGuid method creates a version 4 GUID. It has 122 random bits generated with a cryptographically secure random number generator.

Program.cs
Guid id = Guid.NewGuid();

Console.WriteLine(id);
Console.WriteLine(id.Version);
Console.WriteLine(id.Variant);

Console.WriteLine(Guid.NewGuid());
Console.WriteLine(Guid.NewGuid());

We generate three random GUIDs and print the version and variant of the first one.

Console.WriteLine(id.Version);
Console.WriteLine(id.Variant);

The Version and Variant properties were added in .NET 9. The version is 4 for random GUIDs; in the output, the third group always starts with the digit 4. The Variant property returns the first hexadecimal digit of the fourth group. In RFC 9562 GUIDs the two high bits of that digit are 10, so the value is 8, 9, 10, or 11 and the group starts with 8, 9, a, or b. The chance that two random GUIDs collide is negligible for all practical purposes.

$ dotnet run
0b8859ec-34a8-4fc2-82ff-45e4c03ca12e
4
8
ae2a3321-3564-4fd6-bf5c-027698bca423
60b208d3-b5d8-447b-a405-ac835ce12f02

Formatting

The ToString method accepts a single-letter format specifier.

Program.cs
var id = Guid.Parse("0f8fad5b-d9cb-469f-a165-70867728950e");

string[] formats = ["D", "N", "B", "P", "X"];

foreach (var format in formats)
{
    Console.WriteLine($"{format}: {id.ToString(format)}");
}

Console.WriteLine($"upper: {id.ToString().ToUpperInvariant()}");

We print the same GUID in all five formats.

string[] formats = ["D", "N", "B", "P", "X"];

The D format with hyphens is the default. N omits the hyphens, B and P add braces or parentheses, and X prints the internal structure as hexadecimal constants, a form used in C and C++ source code.

Console.WriteLine($"upper: {id.ToString().ToUpperInvariant()}");

GUIDs are always formatted in lowercase. Some tools, such as Windows and SQL Server, display them in uppercase; we convert the string if we need that form.

$ dotnet run
D: 0f8fad5b-d9cb-469f-a165-70867728950e
N: 0f8fad5bd9cb469fa16570867728950e
B: {0f8fad5b-d9cb-469f-a165-70867728950e}
P: (0f8fad5b-d9cb-469f-a165-70867728950e)
X: {0x0f8fad5b,0xd9cb,0x469f,{0xa1,0x65,0x70,0x86,0x77,0x28,0x95,0x0e}}
upper: 0F8FAD5B-D9CB-469F-A165-70867728950E

Parsing

The Parse and TryParse methods accept all five formats in both lowercase and uppercase. The ParseExact and TryParseExact methods require a specific format.

Program.cs
string[] inputs =
[
    "0f8fad5b-d9cb-469f-a165-70867728950e",
    "0F8FAD5BD9CB469FA16570867728950E",
    "{0f8fad5b-d9cb-469f-a165-70867728950e}",
    "0f8fad5b-d9cb-469f-a165",
    "not a guid"
];

foreach (var input in inputs)
{
    if (Guid.TryParse(input, out Guid id))
    {
        Console.WriteLine($"ok:      {id}");
    }
    else
    {
        Console.WriteLine($"invalid: {input}");
    }
}

Console.WriteLine(Guid.TryParseExact("0F8FAD5BD9CB469FA16570867728950E", "D", out _));
Console.WriteLine(Guid.TryParseExact("0F8FAD5BD9CB469FA16570867728950E", "N", out _));

We try to parse a few strings.

if (Guid.TryParse(input, out Guid id))

The TryParse method returns false for invalid input instead of throwing a FormatException. The parsed GUIDs are equal regardless of the format and case of the input.

Console.WriteLine(Guid.TryParseExact("0F8FAD5BD9CB469FA16570867728950E", "D", out _));
Console.WriteLine(Guid.TryParseExact("0F8FAD5BD9CB469FA16570867728950E", "N", out _));

The string without hyphens is rejected by the D format and accepted by the N format. The exact methods are useful when we validate input that must follow a fixed form.

$ dotnet run
ok:      0f8fad5b-d9cb-469f-a165-70867728950e
ok:      0f8fad5b-d9cb-469f-a165-70867728950e
ok:      0f8fad5b-d9cb-469f-a165-70867728950e
invalid: 0f8fad5b-d9cb-469f-a165
invalid: not a guid
False
True

Empty GUID and equality

Guid is a struct, so its default value is a GUID with all bits set to zero.

Program.cs
Guid g1 = Guid.Empty;
Guid g2 = default;
Guid g3 = Guid.AllBitsSet;
Guid g4 = new("0f8fad5b-d9cb-469f-a165-70867728950e");
Guid g5 = Guid.Parse("0F8FAD5B-D9CB-469F-A165-70867728950E");

Console.WriteLine(g1);
Console.WriteLine(g1 == g2);
Console.WriteLine(g3);
Console.WriteLine(g4 == g5);
Console.WriteLine(g4.Equals(g5));
Console.WriteLine(g1 < g4);

We compare special GUID values and two GUIDs parsed from strings.

Guid g1 = Guid.Empty;
Guid g2 = default;
Guid g3 = Guid.AllBitsSet;

Guid.Empty is the same as the default value. It often stands for a missing identifier. Guid.AllBitsSet, added in .NET 9, is the maximum value; RFC 9562 calls it the Max UUID.

Console.WriteLine(g4 == g5);

GUIDs are compared by value; the case of the source string does not matter.

Console.WriteLine(g1 < g4);

Guid supports comparison operators since .NET 7. The order matches the order of the hexadecimal strings.

$ dotnet run
00000000-0000-0000-0000-000000000000
True
ffffffff-ffff-ffff-ffff-ffffffffffff
True
True
True

Version 7 GUIDs

Random GUIDs are a poor choice for database primary keys: new rows are inserted at random positions in the index, which fragments it. Version 7 GUIDs, available through Guid.CreateVersion7 since .NET 9, begin with a 48-bit Unix timestamp in milliseconds, followed by random bits.

Program.cs
var ids = new List<Guid>();

for (int i = 0; i < 5; i++)
{
    ids.Add(Guid.CreateVersion7());
    Thread.Sleep(2);
}

foreach (var id in ids)
{
    Console.WriteLine(id);
}

Console.WriteLine(ids.SequenceEqual(ids.Order()));

var v4 = Enumerable.Range(0, 5).Select(_ => Guid.NewGuid()).ToList();
Console.WriteLine(v4.SequenceEqual(v4.Order()));

var fast = Enumerable.Range(0, 1000).Select(_ => Guid.CreateVersion7()).ToList();
Console.WriteLine(fast.SequenceEqual(fast.Order()));

We create five version 7 GUIDs with a short pause between them and check whether they are sorted.

ids.Add(Guid.CreateVersion7());
Thread.Sleep(2);

In the output, the first group and the beginning of the second group hold the timestamp. They grow with each GUID, so the list is in ascending order.

var v4 = Enumerable.Range(0, 5).Select(_ => Guid.NewGuid()).ToList();
Console.WriteLine(v4.SequenceEqual(v4.Order()));

Random version 4 GUIDs are in no particular order.

var fast = Enumerable.Range(0, 1000).Select(_ => Guid.CreateVersion7()).ToList();
Console.WriteLine(fast.SequenceEqual(fast.Order()));

GUIDs created within the same millisecond share the timestamp and differ only in the random bits. RFC 9562 allows a counter in these bits, but .NET does not use one, so GUIDs from the same millisecond are not ordered. The ordering is by milliseconds, not strict.

$ dotnet run
01a1e02d-a5eb-7ff2-a5b2-4a93fc3f7ac1
01a1e02d-a5ed-74ea-bd5d-e3d20fb80564
01a1e02d-a5ef-7d69-85c2-6a527ae0279d
01a1e02d-a5f1-7408-b64a-1c9fa680854d
01a1e02d-a5f3-76e7-b61d-bb67b4063e8e
True
False
False

Timestamp of a version 7 GUID

The CreateVersion7 method has an overload that takes the timestamp. We can also read the timestamp back.

Program.cs
var when = new DateTimeOffset(2026, 11, 15, 10, 30, 0, TimeSpan.Zero);
Guid id = Guid.CreateVersion7(when);

Console.WriteLine(id);
Console.WriteLine(GetTimestamp(id).ToString("yyyy-MM-dd HH:mm:ss zzz"));

static DateTimeOffset GetTimestamp(Guid id)
{
    byte[] bytes = id.ToByteArray(bigEndian: true);

    long ms = 0;
    for (int i = 0; i < 6; i++)
    {
        ms = (ms << 8) | bytes[i];
    }

    return DateTimeOffset.FromUnixTimeMilliseconds(ms);
}

We create a GUID for a given time and extract the time from it.

byte[] bytes = id.ToByteArray(bigEndian: true);

We need the bytes in the order in which they appear in the text form. This is the big-endian order.

for (int i = 0; i < 6; i++)
{
    ms = (ms << 8) | bytes[i];
}

The first six bytes form the timestamp in milliseconds since the Unix epoch. The extracted time equals the time we passed in.

$ dotnet run
01a1dec1-b840-7a8a-9469-8cc2a15e53e2
2026-11-15 10:30:00 +00:00

Byte layout

For historical reasons, the ToByteArray method and the Guid(byte[]) constructor store the first three groups in little-endian order.

Program.cs
var id = Guid.Parse("00112233-4455-6677-8899-aabbccddeeff");

Console.WriteLine(Convert.ToHexString(id.ToByteArray()));
Console.WriteLine(Convert.ToHexString(id.ToByteArray(bigEndian: true)));

byte[] raw = Convert.FromHexString("00112233445566778899AABBCCDDEEFF");

Console.WriteLine(new Guid(raw));
Console.WriteLine(new Guid(raw, bigEndian: true));

We convert a GUID with a recognizable pattern to bytes and back.

Console.WriteLine(Convert.ToHexString(id.ToByteArray()));
Console.WriteLine(Convert.ToHexString(id.ToByteArray(bigEndian: true)));

By default, the bytes of the first group (4 bytes), second group (2 bytes), and third group (2 bytes) are reversed. This is the layout used by Windows and SQL Server. The bigEndian parameter, added in .NET 8, gives the RFC 9562 byte order that matches the text form.

Console.WriteLine(new Guid(raw));
Console.WriteLine(new Guid(raw, bigEndian: true));

The same applies when we create a GUID from bytes. When exchanging binary GUIDs with other systems, such as Java, Python, or PostgreSQL, we use the big-endian order.

$ dotnet run
33221100554477668899AABBCCDDEEFF
00112233445566778899AABBCCDDEEFF
33221100-5544-7766-8899-aabbccddeeff
00112233-4455-6677-8899-aabbccddeeff

Name-based GUIDs

Version 5 GUIDs are deterministic: they are computed from a namespace GUID and a name with SHA-1, so the same name always gives the same GUID. .NET does not have a built-in method for them, but the algorithm is short.

Program.cs
using System.Security.Cryptography;
using System.Text;

var dns = Guid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8");

Console.WriteLine(CreateVersion5(dns, "www.example.com"));
Console.WriteLine(CreateVersion5(dns, "www.example.com"));
Console.WriteLine(CreateVersion5(dns, "zetcode.com"));

static Guid CreateVersion5(Guid ns, string name)
{
    byte[] nameBytes = Encoding.UTF8.GetBytes(name);
    byte[] data = [.. ns.ToByteArray(bigEndian: true), .. nameBytes];

    byte[] hash = SHA1.HashData(data);

    hash[6] = (byte)((hash[6] & 0x0F) | 0x50);
    hash[8] = (byte)((hash[8] & 0x3F) | 0x80);

    return new Guid(hash.AsSpan(0, 16), bigEndian: true);
}

We implement version 5 GUIDs and compute them for two domain names in the DNS namespace.

var dns = Guid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8");

RFC 9562 defines a few namespace GUIDs; this one is for domain names.

byte[] data = [.. ns.ToByteArray(bigEndian: true), .. nameBytes];

byte[] hash = SHA1.HashData(data);

We hash the namespace bytes in big-endian order followed by the name in UTF-8.

hash[6] = (byte)((hash[6] & 0x0F) | 0x50);
hash[8] = (byte)((hash[8] & 0x3F) | 0x80);

We set the version bits to 5 and the variant bits to 10. The first 16 bytes of the 20-byte hash form the GUID. The results agree with the uuid.uuid5 function of Python.

$ dotnet run
2ed6657d-e927-568b-95e1-2665a8aea6a2
2ed6657d-e927-568b-95e1-2665a8aea6a2
881419e6-9386-5855-b0a9-1216bdd46c43

Source

Guid struct

RFC 9562: Universally Unique IDentifiers (UUIDs)

In this article we have worked with GUIDs in C#. See also the random, Base64, DateTime, and attributes tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.