Skip to main content
C#

How to Generate GUID in C#

Using System.Guid in .NET

Every C# application eventually needs unique identifiers, and the built-in System.Guid struct handles it without adding a single NuGet package. Call Guid.NewGuid() for a random, RFC 4122-compliant identifier in one line, then reach for Guid.Parse() or Guid.TryParse() whenever you need to turn a string back into a strongly typed Guid. Below you'll find copy-paste ready code for generating a C# GUID, converting a string safely, and the .NET 9 addition for time-sortable identifiers. The powershell uuid page includes UUID generation for Azure DevOps pipelines and PowerShell module development.

Generate GUID in C#

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

How to Generate a UUID in C#

The simplest way to generate a UUID in C# is Guid.NewGuid(), which is built directly into the .NET base class library and uses a cryptographically secure random number generator to produce a 128-bit identifier with virtually zero chance of collision. No package install, no configuration — just call the method. The ruby uuid page includes Sinatra and Hanami UUID patterns alongside full Rails UUID configuration.

Program.cs
using System;

Guid myGuid = Guid.NewGuid();
Console.WriteLine(myGuid);
// Output: 550e8400-e29b-41d4-a716-446655440000

Explanation

Convert a String to a UUID in C#

Sometimes you receive a UUID as a plain string — from a form field, a JSON payload, or a route parameter — and need it back as a proper Guid. C# gives you two ways to do that: Guid.Parse() and Guid.TryParse(). See the rust uuid page for Cargo.toml setup, type-safe UUID generation, and Diesel ORM integration.

Program.cs
using System;

string input = "550e8400-e29b-41d4-a716-446655440000";

// Parse - throws FormatException if the string is invalid
Guid parsed = Guid.Parse(input);

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

Explanation

Other Options for Generating UUIDs in C#

.NET 9 added native support for UUID version 7 through Guid.CreateVersion7(), producing a time-sortable, RFC 9562-compliant identifier that's particularly useful as a database primary key. Combine it with a format specifier when you need a shorter or differently styled string.

Program.cs (.NET 9+)
using System;

// .NET 9+: time-sortable UUID v7, ideal for database primary keys
Guid guidV7 = Guid.CreateVersion7();
Console.WriteLine(guidV7);

// Format without hyphens
string compact = guidV7.ToString("N");

// Format wrapped in braces
string braced = guidV7.ToString("B");

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!