Blog
Wild & Free Tools

How to Generate UUID / GUID in C# and .NET

Last updated: March 2026 6 min read
Quick Answer

Table of Contents

  1. Basic GUID Generation
  2. GUID Format Specifiers
  3. Parse and Validate GUIDs
  4. GUID in Entity Framework Core
  5. GUID in ASP.NET Core
  6. Frequently Asked Questions

In .NET, the type is called Guid (Globally Unique Identifier), not UUID — but it is the same standard: 128 bits, the same 8-4-4-4-12 hyphenated format, RFC 4122 compatible. This guide covers generation, all string format specifiers, Entity Framework Core integration, and ASP.NET Core patterns.

Generate a GUID in C# — Basic Usage

using System;

// Generate a new GUID:
Guid id = Guid.NewGuid();
Console.WriteLine(id);
// Output: 550e8400-e29b-41d4-a716-446655440000

// As a string directly:
string guid = Guid.NewGuid().ToString();
// "550e8400-e29b-41d4-a716-446655440000"

// Empty GUID (all zeros — useful as a null sentinel):
Guid empty = Guid.Empty;
// 00000000-0000-0000-0000-000000000000

Guid.NewGuid() uses CryptGenRandom on Windows and equivalent secure random sources on Linux/macOS — it is cryptographically secure.

GUID String Format Specifiers (N, D, B, P, X)

C# provides five format specifiers for Guid.ToString():

Guid g = Guid.NewGuid();

g.ToString("D");  // Default — hyphens, lowercase
// "550e8400-e29b-41d4-a716-446655440000"

g.ToString("N");  // No dashes — 32 hex chars
// "550e8400e29b41d4a716446655440000"

g.ToString("B");  // Braces — {550e8400-e29b-41d4-a716-446655440000}
// "{550e8400-e29b-41d4-a716-446655440000}"

g.ToString("P");  // Parentheses
// "(550e8400-e29b-41d4-a716-446655440000)"

g.ToString("X");  // Hexadecimal with 0x prefix
// "{0x550e8400,0xe29b,0x41d4,{0xa7,0x16,0x44,0x66,0x55,0x44,0x00,0x00}}"

// Uppercase:
g.ToString("D").ToUpper();
// "550E8400-E29B-41D4-A716-446655440000"

The "N" format is the most common choice when you need a UUID without dashes (URL slugs, filenames, database keys in non-UUID column types).

Sell Custom Apparel — We Handle Printing & Free Shipping

Parse and Validate GUID Strings in C#

// Parse — throws FormatException if invalid:
Guid parsed = Guid.Parse("550e8400-e29b-41d4-a716-446655440000");

// TryParse — safe, returns bool:
if (Guid.TryParse(input, out Guid result)) {
    Console.WriteLine($"Valid: {result}");
} else {
    Console.WriteLine("Invalid GUID format");
}

// TryParseExact — enforce a specific format:
Guid.TryParseExact(input, "N", out Guid noDashResult);
// Only passes if input is in the no-dashes N format

Guid.TryParse() accepts all five format specifiers plus uppercase variants — it is lenient about hyphens and case. Use TryParseExact when you need to enforce a specific format from an external system.

GUID as Primary Key in Entity Framework Core

Entity Framework Core has first-class GUID support. The simplest approach:

public class Order {
    public Guid Id { get; set; } = Guid.NewGuid();
    public string Status { get; set; } = string.Empty;
}

// In DbContext configuration — EF Core handles GUID columns automatically:
protected override void OnModelCreating(ModelBuilder modelBuilder) {
    modelBuilder.Entity<Order>()
        .HasKey(o => o.Id);
    // No explicit type needed — EF maps Guid to UNIQUEIDENTIFIER (SQL Server)
    // or uuid (PostgreSQL) automatically
}

With SQL Server, EF Core maps Guid to UNIQUEIDENTIFIER natively — 16 bytes, no conversion needed.

With PostgreSQL (Npgsql), EF Core maps Guid to the native uuid type automatically.

Performance note: On SQL Server, consider using newsequentialid() at the database level or a sequential GUID library to avoid index fragmentation from random UUIDs:

modelBuilder.Entity<Order>()
    .Property(o => o.Id)
    .HasDefaultValueSql("newsequentialid()");

GUID in ASP.NET Core — Route Parameters and API

// Controller with GUID route parameter:
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase {

    [HttpGet("{id:guid}")]
    public IActionResult GetOrder(Guid id) {
        // :guid constraint validates format automatically
        // Returns 404 Not Found if format is invalid (not 400)
        var order = _service.GetById(id);
        return order == null ? NotFound() : Ok(order);
    }

    [HttpPost]
    public IActionResult CreateOrder(CreateOrderDto dto) {
        var id = Guid.NewGuid();
        _service.Create(id, dto);
        return CreatedAtAction(nameof(GetOrder), new { id }, null);
    }
}

// In minimal APIs (ASP.NET Core 6+):
app.MapGet("/orders/{id:guid}", (Guid id) => {
    return Results.Ok(orderService.GetById(id));
});

The :guid route constraint validates the format automatically. Invalid GUIDs in the URL return a 404 (not found) rather than a 400 — to return 400, add a custom constraint or validate manually in the action.

Generate a GUID Without Writing Any Code

The Cheetah UUID Generator produces RFC-compliant UUID v4 values instantly — paste into your C# test, migration seed, or config file.

Open Free UUID Generator

Frequently Asked Questions

Is GUID the same as UUID in C#?

Yes. GUID (Globally Unique Identifier) is Microsoft's name for the same standard. A C# Guid is structurally identical to a UUID v4 — same 128 bits, same hyphenated string format. The terms are interchangeable in practice.

What does Guid.ToString("N") produce?

A 32-character lowercase hex string with no hyphens: "550e8400e29b41d4a716446655440000". The "N" specifier is the equivalent of stripping hyphens from the default format.

Should I use Guid.NewGuid() or new Guid() in C#?

Use Guid.NewGuid() to generate a random GUID. new Guid() creates Guid.Empty (all zeros) — it is a struct constructor, not a generator. The two do very different things.

How do I generate a sequential GUID in .NET to avoid index fragmentation?

Use HasDefaultValueSql("newsequentialid()") in Entity Framework to let SQL Server generate sequential GUIDs. Alternatively, use a library like UuidCreator or RT.Comb for application-level sequential GUIDs.

Can I use Guid as a primary key in .NET with MySQL?

Yes, but MySQL has no native GUID type — EF Core maps it to CHAR(36) by default. For better performance, configure BINARY(16) storage with a value converter in your DbContext.

Chris Hartley
Chris Hartley SEO & Marketing Writer

Chris has been in digital marketing for twelve years covering SEO tools and content optimization.

More articles by Chris →
Launch Your Own Clothing Brand — No Inventory, No Risk