C#

How to Generate GUID in C#

Using System.Guid in .NET

Generate and work with GUIDs (Globally Unique Identifiers) in C# using the built-in System.Guid struct. In .NET, GUID is equivalent to UUID and provides extensive support for parsing, formatting, and database integration.

Generate GUID in C#

Guid.NewGuid()
550e8400-e29b-41d4-a716-446655440000

Quick Start - Generate GUID

The simplest way to generate a GUID in C# using Guid.NewGuid():

C#
// Generate random GUID (equivalent to UUID v4)
Guid guid = Guid.NewGuid();
Console.WriteLine(guid);  
// Output: 550e8400-e29b-41d4-a716-446655440000

// Use in variable
var userId = Guid.NewGuid();
var orderId = Guid.NewGuid();

Console.WriteLine($"User ID: {userId}");
Console.WriteLine($"Order ID: {orderId}");

GUID vs UUID: In .NET, they're the same thing. GUID is Microsoft's terminology, but System.Guid follows the UUID standard (RFC 4122).

GUID String Formats

Convert GUIDs to different string formats:

C#
Guid id = Guid.NewGuid();

// Convert to string formats
string standard = id.ToString();      
// 550e8400-e29b-41d4-a716-446655440000

string formatD = id.ToString("D");    
// 550e8400-e29b-41d4-a716-446655440000 (default)

string formatN = id.ToString("N");    
// 550e8400e29b41d4a716446655440000 (no hyphens)

string formatB = id.ToString("B");    
// {550e8400-e29b-41d4-a716-446655440000} (braces)

string formatP = id.ToString("P");    
// (550e8400-e29b-41d4-a716-446655440000) (parentheses)

string formatX = id.ToString("X");    
// {0x550e8400,0xe29b,0x41d4,{0xa7,0x16,0x44,0x66,0x55,0x44,0x00,0x00}}

// Uppercase
string upper = id.ToString().ToUpper();

// Generate multiple GUIDs
var guids = Enumerable.Range(0, 10)
    .Select(_ => Guid.NewGuid())
    .ToList();

Parse GUID from String

Parse and validate GUID strings:

C#
// Parse (throws exception if invalid)
Guid guid = Guid.Parse("550e8400-e29b-41d4-a716-446655440000");
Console.WriteLine($"Parsed: {guid}");

// TryParse (returns bool, no exception)
string input = "550e8400-e29b-41d4-a716-446655440000";
if (Guid.TryParse(input, out Guid result))
{
    Console.WriteLine($"Valid GUID: {result}");
}
else
{
    Console.WriteLine("Invalid GUID format");
}

// ParseExact with format specifier
Guid exact = Guid.ParseExact("{550e8400-e29b-41d4-a716-446655440000}", "B");

// TryParseExact
if (Guid.TryParseExact(input, "D", out Guid exactResult))
{
    Console.WriteLine($"Exact parse: {exactResult}");
}

// From byte array
byte[] bytes = new byte[16];
Guid fromBytes = new Guid(bytes);

Empty GUID & Comparison

C#
// Empty GUID (all zeros) - equivalent to Nil UUID
Guid empty = Guid.Empty;
Console.WriteLine(empty);  
// 00000000-0000-0000-0000-000000000000

// Check if empty
Guid myGuid = Guid.NewGuid();
if (myGuid == Guid.Empty)
{
    Console.WriteLine("GUID is empty");
}

// Compare GUIDs
Guid g1 = Guid.NewGuid();
Guid g2 = Guid.NewGuid();

Console.WriteLine(g1 == g2);           // false (usually)
Console.WriteLine(g1.Equals(g2));      // false
Console.WriteLine(g1.CompareTo(g2));   // -1, 0, or 1

// Default value for Guid is Empty
Guid defaultGuid = default;  // Same as Guid.Empty
Guid defaultGuid2 = default(Guid);

GUID v7 in .NET 9+

.NET 9 introduces support for UUID v7 (time-sortable GUIDs):

C# (.NET 9+)
// Generate UUID v7 (time-ordered)
Guid guidV7 = Guid.CreateVersion7();

// With specific timestamp
DateTimeOffset timestamp = DateTimeOffset.UtcNow;
Guid guidV7WithTime = Guid.CreateVersion7(timestamp);

// Get version
int version = guidV7.Version;  // 7 for v7, 4 for v4

// Sort by creation time
var sortedGuids = new List
{
    Guid.CreateVersion7(),
    Guid.CreateVersion7(),
    Guid.CreateVersion7()
}.OrderBy(g => g).ToList();

For .NET 8 and earlier: Use the UUIDNext NuGet package for v7 support: Install-Package UUIDNext

Entity Framework Core Integration

Use GUIDs as primary keys in Entity Framework Core:

C# - Entity Framework Core
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    
    [Required]
    [MaxLength(100)]
    public string Name { get; set; }
    
    [Required]
    [MaxLength(255)]
    public string Email { get; set; }
    
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

public class AppDbContext : DbContext
{
    public DbSet Users { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // SQL Server: use NEWSEQUENTIALID() for better performance
        modelBuilder.Entity()
            .Property(u => u.Id)
            .HasDefaultValueSql("NEWSEQUENTIALID()");
        
        // PostgreSQL: use gen_random_uuid()
        // .HasDefaultValueSql("gen_random_uuid()");
    }
}

// Alternative: Generate GUID in code
public class Product
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public string Name { get; set; }
}

// Usage
using (var context = new AppDbContext())
{
    var user = new User 
    { 
        Name = "Bob Wilson", 
        Email = "bob@example.com" 
    };
    
    context.Users.Add(user);
    await context.SaveChangesAsync();
    
    Console.WriteLine($"Created user with ID: {user.Id}");
}

ASP.NET Core Web API

Use GUIDs in Web API controllers and routing:

C# - ASP.NET Core
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly AppDbContext _context;
    
    public UsersController(AppDbContext context)
    {
        _context = context;
    }
    
    [HttpGet("{id:guid}")]
    public async Task GetUser(Guid id)
    {
        // id is automatically parsed from route
        var user = await _context.Users.FindAsync(id);
        
        if (user == null)
            return NotFound();
        
        return Ok(user);
    }
    
    [HttpPost]
    public async Task CreateUser([FromBody] CreateUserDto dto)
    {
        var user = new User
        {
            Id = Guid.NewGuid(),
            Name = dto.Name,
            Email = dto.Email
        };
        
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        
        return CreatedAtAction(
            nameof(GetUser), 
            new { id = user.Id }, 
            user
        );
    }
    
    [HttpPut("{id:guid}")]
    public async Task UpdateUser(
        Guid id, 
        [FromBody] UpdateUserDto dto)
    {
        var user = await _context.Users.FindAsync(id);
        if (user == null)
            return NotFound();
        
        user.Name = dto.Name;
        user.Email = dto.Email;
        
        await _context.SaveChangesAsync();
        return NoContent();
    }
    
    [HttpDelete("{id:guid}")]
    public async Task DeleteUser(Guid id)
    {
        var user = await _context.Users.FindAsync(id);
        if (user == null)
            return NotFound();
        
        _context.Users.Remove(user);
        await _context.SaveChangesAsync();
        
        return NoContent();
    }
}

Convert To/From Bytes

C#
Guid guid = Guid.NewGuid();

// To byte array (16 bytes)
byte[] bytes = guid.ToByteArray();
Console.WriteLine($"Byte array length: {bytes.Length}");  // 16

// From byte array
Guid fromBytes = new Guid(bytes);

// To Base64 (shorter string representation)
string base64 = Convert.ToBase64String(guid.ToByteArray());
Console.WriteLine($"Base64: {base64}");
// Example: "AISEDuKbQdSnFkRmVUQAAA=="

// From Base64
byte[] base64Bytes = Convert.FromBase64String(base64);
Guid fromBase64 = new Guid(base64Bytes);

// Span support (.NET Core 2.1+)
Span span = stackalloc byte[16];
guid.TryWriteBytes(span);

Guid fromSpan = new Guid(span);

ADO.NET Database Operations

C# - ADO.NET
using System.Data.SqlClient;

public class UserRepository
{
    private string _connectionString;
    
    public async Task CreateUser(string name, string email)
    {
        using var conn = new SqlConnection(_connectionString);
        await conn.OpenAsync();
        
        var cmd = new SqlCommand(
            "INSERT INTO users (id, name, email) OUTPUT INSERTED.id VALUES (@id, @name, @email)", 
            conn
        );
        
        var userId = Guid.NewGuid();
        cmd.Parameters.AddWithValue("@id", userId);
        cmd.Parameters.AddWithValue("@name", name);
        cmd.Parameters.AddWithValue("@email", email);
        
        var returnedId = (Guid)await cmd.ExecuteScalarAsync();
        return returnedId;
    }
    
    public async Task GetUserById(Guid id)
    {
        using var conn = new SqlConnection(_connectionString);
        await conn.OpenAsync();
        
        var cmd = new SqlCommand(
            "SELECT id, name, email FROM users WHERE id = @id", 
            conn
        );
        
        cmd.Parameters.Add("@id", System.Data.SqlDbType.UniqueIdentifier).Value = id;
        
        using var reader = await cmd.ExecuteReaderAsync();
        if (await reader.ReadAsync())
        {
            return new User
            {
                Id = reader.GetGuid(0),
                Name = reader.GetString(1),
                Email = reader.GetString(2)
            };
        }
        
        return null;
    }
}

Other Programming Language UUID Guides

Copied!