Appearance
Generate UUID in C#
The simplest way to generate a UUID in C# is to use the built-in System.Guid class and call its static method NewGuid(). This produces a valid version 4 UUID.
csharp
using System;
class Program
{
static void Main()
{
Guid uuid = Guid.NewGuid();
Console.WriteLine($"Generated UUID: {uuid}");
}
}If you need to generate a specific UUID version, you can use a third-party library such as UuidCreator which offers more flexible options:
csharp
using UuidCreator;
// Generate UUID version 1 - time based
var uuid1 = TimeBasedUuidCreator.GetTimeBasedUuid();
// Generate UUID version 3 - deterministic and hashed with MD5
var uuid3 = NameBasedUuidCreator.GetNameBasedUuid(NameBasedUuidCreator.NAMESPACE_URL, "https://example.com");
// Generate UUID version 4 - random
var uuid4 = RandomBasedUuidCreator.GetRandomBasedUuid();
// Generate UUID version 5 - deterministic and hashed with SHA-1
var uuid5 = NameBasedUuidCreator.GetNameBasedUuid5(NameBasedUuidCreator.NAMESPACE_URL, "https://example.com");
// Generate UUID version 6 - time-ordered
var uuid6 = TimeOrderedUuidCreator.GetTimeOrderedUuid();
// Generate UUID version 7 - time-ordered with random
var uuid7 = TimeOrderedUuidCreator.GetTimeOrderedEpochUuid();Installation & Setup
NuGet Package Manager:
bash
Install-Package UuidCreatorPackage Manager Console:
bash
dotnet add package UuidCreator.NET Core vs .NET Framework
Both .NET Core and .NET Framework support System.Guid.NewGuid() for UUID v4 generation. For other versions, use the UuidCreator library which supports:
- .NET Standard 2.0+
- .NET Core 2.0+
- .NET Framework 4.6.1+
UUID Version Comparison
Choose the right version for your C# application:
- Version 1 - Time-based, includes MAC address
- Version 3 - MD5 namespace-based, deterministic
- Version 4 - Random, most popular choice
- Version 5 - SHA-1 namespace-based, more secure than v3
- Version 6 - Time-ordered, better than v1 for databases
- Version 7 - Modern time-based with improved sorting
For C# applications:
- ASP.NET Core APIs: Use Version 4 for entity identifiers
- Entity Framework: Consider Version 7 for better database performance
- Microservices: Use Version 6 for distributed system ordering
How do I generate UUID in other languages?
Microsoft ecosystem:
- TypeScript - Frontend development with .NET APIs
Cross-platform development:
- JavaScript - crypto.randomUUID() & uuid library
- Python - Built-in uuid module
- Java - java.util.UUID & UuidCreator
- Go - google/uuid package
- Rust - uuid crate