public readonly partial struct UUID : IEquatable<UUID>, IComparable<UUID>, IComparable
-
-
-
Properties
-
-
-
-
Property
-
Type
-
Description
-
-
-
Empty
-
UUID
-
Gets the empty UUID value (all zeros)
-
-
-
Version
-
byte
-
Gets the UUID version number (7 for UUIDv7)
-
-
-
Variant
-
byte
-
Gets the UUID variant number (2 for RFC 4122)
-
-
-
Time
-
DateTimeOffset
-
Gets the timestamp embedded in the UUID (UUIDv7 only)
-
-
-
-
-
Constructors
-
-
// Create a new random UUID
-public UUID()
-
-// Create from bytes
-public UUID(ReadOnlySpan<byte> bytes)
-
-// Create from string
-public static UUID Parse(string input)
-public static UUID Parse(ReadOnlySpan<char> input)
-
-// Try parse from string
-public static bool TryParse(string input, out UUID result)
-public static bool TryParse(ReadOnlySpan<char> input, out UUID result)
-
-
-
-
-
Methods
-
-
String Formatting
-
-
// Convert to standard string format
-public override string ToString()
-
-// Convert to Base32 format
-public string ToBase32()
-
-// Convert to Base64 format
-public string ToBase64()
-
-// Convert from Base64 format
-public static UUID FromBase64(string base64)
-public static bool TryFromBase64(string base64, out UUID result)
// Generate a new UUID
-var id = new UUID();
-
-// Different string formats
-Console.WriteLine(id.ToString()); // Standard format
-Console.WriteLine(id.ToBase64()); // Base64 format
-Console.WriteLine(id.ToBase32()); // Base32 format
-Console.WriteLine(id.Int64()); // Int64 format
-
-// Get raw bytes
-byte[] bytes = id.ToByteArray();
-
-
This example shows different ways to create and format UUIDs.
-
-
-
-
Parse UUIDs
-
-
// Parse from string
-var id1 = UUID.Parse("0123456789abcdef0123456789abcdef");
-
-// Try parse pattern
-if (UUID.TryParse("0123456789abcdef0123456789abcdef", out var id2))
-{
- Console.WriteLine("Successfully parsed: " + id2);
-}
-
-
Examples of parsing UUIDs from different string formats.
-
-
-
-
-
Advanced Examples
-
-
-
Bulk UUID Generation
-
-
// Generate multiple UUIDs efficiently
-UUID[] uuids = new UUID[1000];
-ArrayExtension.Fill(uuids);
-
-// Process in parallel
-Parallel.ForEach(uuids, uuid =>
-{
- ProcessUUID(uuid);
-});
-
-private void ProcessUUID(UUID uuid)
-{
- // Your processing logic here
- var str = uuid.ToString();
- // ...
-}
-
-
Example of generating and processing multiple UUIDs efficiently.
-
-
-
-
Custom Formatting
-
-
var uuid = new UUID();
-
-// Custom string builder formatting
-var sb = new StringBuilder();
-sb.Append("UUID-");
-sb.Append(uuid.ToString());
-sb.Append("-END");
-
-// Format with prefix
-string prefixed = $"ID_{uuid}";
-
-
Examples of custom UUID string formatting.
-
-
-
-
-
String Format Examples
-
-
-
String Format Conversions
-
-
// Create a new UUID
-var id = new UUID();
-
-// Convert to different formats
-string standard = id.ToString();
-string base64 = id.ToBase64();
-string base32 = id.ToBase32();
-long int64 = id.ToInt64();
-
-Console.WriteLine($"Standard: {standard}");
-Console.WriteLine($"Base64: {base64}");
-Console.WriteLine($"Base32: {base32}");
-Console.WriteLine($"Int64: {int64}");
-
-// Convert back from Base64
-UUID fromBase64 = UUID.FromBase64(base64);
-Console.WriteLine($"Restored from Base64: {fromBase64}");
-
-// Safe parsing from Base64
-if (UUID.TryFromBase64(base64, out UUID parsed))
-{
- Console.WriteLine($"Successfully parsed from Base64: {parsed}");
-}
-
-
Examples of converting UUIDs to and from different string formats.
-
-
-
-
Byte Array Operations
-
-
// Create a new UUID
-var id = new UUID();
-
-// Convert to byte array
-byte[] bytes = id.ToByteArray();
-Console.WriteLine($"As bytes: {BitConverter.ToString(bytes)}");
-
-// Convert back from bytes
-UUID fromBytes = UUID.FromByteArray(bytes);
-Console.WriteLine($"Restored from bytes: {fromBytes}");
-
-// Safe conversion with TryFromByteArray
-if (UUID.TryFromByteArray(bytes, out UUID parsed))
-{
- Console.WriteLine($"Successfully parsed from bytes: {parsed}");
-}
-
-// Write directly to a byte array
-byte[] destination = new byte[16];
-if (id.TryWriteBytes(destination))
-{
- Console.WriteLine($"Successfully wrote to byte array: {BitConverter.ToString(destination)}");
-}
-
-
Examples of working with byte array representations of UUIDs.
-
-
-
-
Guid Conversions
-
-
// Create a new UUID
-var uuid = new UUID();
-
-// Implicit conversion to Guid
-Guid guid = uuid;
-Console.WriteLine($"As Guid: {guid}");
-
-// Implicit conversion from Guid
-UUID fromGuid = guid;
-Console.WriteLine($"Back to UUID: {fromGuid}");
-
-// Using explicit methods
-Guid guidExplicit = uuid.ToGuid();
-UUID uuidExplicit = UUID.FromGuid(guidExplicit);
-
-
Examples of converting between UUID and Guid types.
-
-
-
-
-
Database Examples
-
-
-
Entity Framework Core
-
-
public class User
-{
- public UUID Id { get; set; }
- public string Name { get; set; }
-}
-
-public class AppDbContext : DbContext
-{
- public DbSet<User> Users { get; set; }
-
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- modelBuilder.Entity<User>()
- .Property(e => e.Id)
- .HasConversion(
- v => v.ToString(),
- v => UUID.Parse(v));
- }
-}
-
-
Example of using UUIDs with Entity Framework Core.
-
-
-
-
Dapper
-
-
public async Task<User> GetUser(UUID id)
-{
- using var connection = new SqlConnection(connectionString);
- return await connection.QuerySingleOrDefaultAsync<User>(
- "SELECT * FROM Users WHERE Id = @Id",
- new { Id = id.ToString() }
- );
-}
-
-
Example of using UUIDs with Dapper.
-
-
-
-
-
Web API Examples
-
-
-
ASP.NET Core Controller
-
-
public class UserController : ControllerBase
-{
- [HttpGet("{id}")]
- public async Task<ActionResult<User>> GetUser(UUID id)
- {
- var user = await _userService.GetUserAsync(id);
- if (user == null)
- return NotFound();
- return user;
- }
-
- [HttpPost]
- public async Task<ActionResult<User>> CreateUser(User user)
- {
- user.Id = new UUID(); // Generate new UUID
- await _userService.CreateUserAsync(user);
- return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
- }
-}
UUID (Universally Unique Identifier) is a 128-bit identifier that's guaranteed to be unique across space and time. Our UUID library provides a high-performance, secure implementation for .NET applications.
-
-
-
-
How is UUID different from Guid?
-
While UUID and Guid represent the same concept, our UUID implementation offers:
-
-
Better performance (up to 70% faster)
-
More modern API design
-
Additional string format options (Base32, Base64)
-
Better security by default
-
-
-
-
-
Is UUID thread-safe?
-
Yes, UUID operations are thread-safe. You can safely generate and manipulate UUIDs from multiple threads without any synchronization.
-
-
-
-
-
Usage Questions
-
-
-
How do I generate a new UUID?
-
-
// Simple generation
-var uuid = new UUID();
-
-// Generate multiple
-UUID[] uuids = new UUID[1000];
-ArrayExtension.Fill(uuids);
-
-
-
-
-
What string formats are supported?
-
-
var uuid = new UUID();
-
-// Standard format (default)
-Console.WriteLine(uuid.ToString());
-// "0123456789abcdef0123456789abcdef"
-
-// Base32 (URL-safe)
-Console.WriteLine(uuid.ToBase32());
-// "028T5CY4TQKFF028T5CY4TQKFF"
-
-// Base64
-Console.WriteLine(uuid.ToBase64());
-// "782riWdFIwHvzauJZ0UjAQ=="
Always use Try* methods when parsing untrusted input to handle errors gracefully.
-
-
-
-
How do I use UUIDs with Entity Framework?
-
-
public class User
-{
- public UUID Id { get; set; }
- public string Name { get; set; }
-}
-
-protected override void OnModelCreating(ModelBuilder modelBuilder)
-{
- modelBuilder.Entity<User>()
- .Property(e => e.Id)
- .HasConversion(
- v => v.ToByteArray(),
- v => new UUID(v));
-}
-
-
-
-
-
-
Performance Questions
-
-
-
How many UUIDs can be generated per second?
-
On a modern system:
-
-
Single thread: ~20.5M UUIDs/second
-
Multi-thread (4 cores): ~78.2M UUIDs/second
-
Multi-thread (8 cores): ~152.3M UUIDs/second
-
-
-
-
-
How can I improve UUID generation performance?
-
For best performance:
-
-
Use bulk generation methods for multiple UUIDs
-
Reuse UUID instances when possible
-
Use TryParse instead of Parse
-
Store UUIDs in binary format
-
-
-
-
-
-
Troubleshooting
-
-
-
Why am I getting a FormatException?
-
FormatException occurs when parsing invalid UUID strings. Common issues:
-
-
Incorrect string format
-
Missing or extra hyphens
-
Invalid characters
-
-
Solution: Use TryParse for safer parsing:
-
-
if (UUID.TryParse(input, out var uuid))
-{
- // Valid UUID
-}
-else
-{
- // Invalid format
-}
-
-
-
-
-
How do I migrate from Guid?
-
UUID provides implicit conversion operators:
-
-
// From Guid to UUID
-Guid guid = Guid.NewGuid();
-UUID uuid = guid; // Implicit conversion
-
-// From UUID to Guid
-UUID uuid = new UUID();
-Guid guid = uuid; // Implicit conversion
Here's how to get started with basic UUID operations:
-
-
-
// Generate a new UUID
-var id = new UUID();
-
-// Convert to string
-string str = id.ToString(); // "0123456789abcdef0123456789abcdef"
-
-// Parse from string
-UUID parsed = UUID.Parse("0123456789abcdef0123456789abcdef");
-
-// Check UUID version and variant
-Console.WriteLine($"Version: {id.Version}"); // 7 (UUIDv7)
-Console.WriteLine($"Variant: {id.Variant}"); // 2 (RFC 4122)
-
-// Get timestamp from UUID
-Console.WriteLine($"Time: {id.Time:yyyy-MM-dd HH:mm:ss.fff}");
-
-
-
-
-
-
String Formats
-
UUID supports multiple string formats for different use cases:
-
-
-
var uuid = new UUID();
-
-// Standard format
-string standard = uuid.ToString();
-// "0123456789abcdef0123456789abcdef"
-
-// Int64 format
-long int64 = uuid.ToInt64();
-// "40992764608247672"
-
-// Base32 format (URL-safe)
-string base32 = uuid.ToBase32();
-// "028T5CY4TQKFF028T5CY4TQKFF"
-
-// Base64 format
-string base64 = uuid.ToBase64();
-// "782riWdFIwHvzauJZ0UjAQ=="
-
-// Convert Base64 back to UUID
-UUID fromBase64 = UUID.FromBase64(base64);
-Console.WriteLine($"Base64 -> UUID: {fromBase64}");
-
-// Safe parsing with TryFromBase64
-if (UUID.TryFromBase64(base64, out UUID parsedFromBase64))
-{
- Console.WriteLine($"Successfully parsed from Base64: {parsedFromBase64}");
-}
-
-
-
-
-
Bulk Operations
-
For high-performance scenarios where you need to generate multiple UUIDs efficiently:
-
-
-
// Fill an existing array with UUIDs
-UUID[] uuids = new UUID[1000];
-uuids.Fill(); // Thread-safe, efficient bulk generation
-
-// Generate a new array of UUIDs
-UUID[] generated = ArrayExtension.Generate(1000);
-
-// With error handling
-if (ArrayExtension.TryGenerate(1000, out UUID[]? result))
-{
- foreach (var uuid in result)
- {
- // Process each UUID
- Console.WriteLine(uuid);
- }
-}
-
-
-
-
Performance Tips
-
-
Use Fill() for existing arrays to avoid allocation overhead
-
Use TryGenerate() for safe bulk generation with error handling
-
All bulk operations are thread-safe and optimized for concurrent use
-
-
-
-
-
-
Byte Array Operations
-
UUID provides methods for converting to and from byte arrays:
-
-
-
// Convert UUID to byte array
-UUID id = UUID.New();
-byte[] bytes = id.ToByteArray();
-Console.WriteLine($"UUID -> Bytes: {BitConverter.ToString(bytes)}");
-
-// Convert byte array back to UUID
-UUID fromBytes = UUID.FromByteArray(bytes);
-Console.WriteLine($"Bytes -> UUID: {fromBytes}");
-
-// Safe parsing with TryFromByteArray
-if (UUID.TryFromByteArray(bytes, out UUID parsedFromBytes))
-{
- Console.WriteLine($"Successfully parsed from bytes: {parsedFromBytes}");
-}
-
-// Writing directly to a byte array
-byte[] destination = new byte[16];
-if (id.TryWriteBytes(destination))
-{
- Console.WriteLine($"Successfully wrote to byte array: {BitConverter.ToString(destination)}");
-}
-
-
-
-
-
Performance Tips
-
-
-
String Formatting
-
-
Use appropriate string format methods based on your needs
-
Consider using Base32 for URL-safe strings
-
-
-
-
-
Bulk Operations
-
-
Use array pooling for bulk operations
-
Consider parallel processing for large batches
-
-
-
-
-
Memory Usage
-
-
UUID struct is optimized for minimal memory footprint
Take advantage of parallel processing for bulk operations:
-
-
// Process UUIDs in parallel
-Parallel.ForEach(uuids, uuid =>
-{
- ProcessUUID(uuid);
-});
-
-
-
-
-
String Conversions
-
Choose the right string format for your use case:
-
-
// Base32 is URL-safe and compact
-string base32 = uuid.ToBase32(); // Most efficient for URLs
-
-// Base64 is compact but may need URL encoding
-string base64 = uuid.ToBase64(); // Most space-efficient
-
-// Standard format is human-readable
-string standard = uuid.ToString(); // Most readable
-
-
-
-
-
Byte Array Operations
-
Use the most efficient byte array methods:
-
-
// Pre-allocate buffer for multiple writes
-byte[] buffer = new byte[16];
-if (uuid.TryWriteBytes(buffer))
-{
- // Use buffer directly without allocation
- ProcessBytes(buffer);
-}
-
-// For single use, ToByteArray is simpler
-byte[] bytes = uuid.ToByteArray();
-
-
-
-
-
Guid Conversions
-
Take advantage of implicit conversions:
-
-
// Implicit conversion is most efficient
-UUID uuid = new UUID();
-Guid guid = uuid; // No explicit conversion needed
-
-// Avoid unnecessary conversions
-void ProcessId(UUID uuid)
-{
- // Don't convert if UUID is accepted
- ProcessUUID(uuid);
-
- // Convert only when Guid is required
- ProcessGuid(uuid); // Implicit conversion
-}
-
-
-
-
-
-
Performance Comparison
-
-
-
-
-
Operation
-
UUID
-
Guid
-
Improvement
-
-
-
Generation
-
20.5M/s
-
12.3M/s
-
+66%
-
-
-
Parse
-
15.8M/s
-
8.9M/s
-
+77%
-
-
-
ToString
-
12.3M/s
-
7.2M/s
-
+70%
-
-
-
-
-
-
-
Best Practices
-
-
-
Do
-
-
Use array pooling for bulk operations
-
Take advantage of Span<T> APIs
-
Use TryParse over Parse when possible
-
Cache frequently used UUIDs
-
-
-
-
-
Don't
-
-
Generate UUIDs in tight loops individually
-
Convert to string unnecessarily
-
Parse the same UUID repeatedly
-
Ignore the available bulk operations
-
-
-
-
-
-
Profiling Tools
-
-
-
BenchmarkDotNet
-
Our benchmarks are created using BenchmarkDotNet. You can run them yourself:
-
-
public class UUIDBenchmarks
-{
- [Benchmark]
- public void GenerateUUID()
- {
- var uuid = new UUID();
- }
-
- [Benchmark]
- public void ParseUUID()
- {
- UUID.Parse("0123456789abcdef0123456789abcdef");
- }
-}
UUID library is designed with security in mind, using cryptographically secure random number generation by default.
-
-
-
Key Security Features
-
-
Cryptographically secure random number generation
-
Protection against timing attacks
-
Safe string parsing and validation
-
Thread-safe operations
-
-
-
-
-
-
Random Number Generation
-
-
-
Secure Generation
-
UUID uses System.Security.Cryptography.RandomNumberGenerator for secure random number generation:
-
-
// Automatically uses secure RNG
-var uuid = new UUID();
-
-// For bulk operations
-UUID[] uuids = new UUID[1000];
-ArrayExtension.Fill(uuids); // Still uses secure RNG
-
-
-
-
-
-
Security Best Practices
-
-
-
Recommended Practices
-
-
Always validate UUID inputs
-
Use TryParse for untrusted input
-
Store UUIDs in their binary form when possible
-
Use URL-safe Base32 encoding for web contexts
-
-
-
-
-
Practices to Avoid
-
-
Don't use UUIDs for sensitive data encoding
-
Don't use UUIDs as security tokens
-
Don't assume sequential UUIDs are secure
-
Don't expose internal UUID representation
-
-
-
-
-
-
Input Validation
-
-
-
Safe Parsing
-
Always use TryParse for untrusted input:
-
-
// Safe parsing of untrusted input
-public bool ValidateUserInput(string input)
-{
- if (UUID.TryParse(input, out var uuid))
- {
- // Input is a valid UUID
- ProcessValidUUID(uuid);
- return true;
- }
- return false;
-}
-
-
-
-
-
-
Secure Storage
-
-
-
Database Storage
-
Best practices for storing UUIDs in databases:
-
-
-- SQL Server
-CREATE TABLE Users (
- Id BINARY(16) PRIMARY KEY, -- Most efficient
- -- or
- Id UNIQUEIDENTIFIER PRIMARY KEY -- If you need native UUID type
-);
-
-
-
-
-
Entity Framework
-
Configure EF Core for secure UUID handling:
-
-
protected override void OnModelCreating(ModelBuilder modelBuilder)
-{
- modelBuilder.Entity<User>()
- .Property(e => e.Id)
- .HasConversion(
- v => v.ToByteArray(), // Store as binary
- v => new UUID(v));
-}
-
-
-
-
-
-
Cryptographic Notes
-
-
-
Important Security Notes
-
-
UUIDs are not suitable for cryptographic purposes
-
Do not use UUIDs to store sensitive information
-
UUIDs are not guaranteed to be unique across systems
-
Use proper cryptographic functions for security-critical operations
Example of serializing and deserializing arrays of UUIDs using System.Text.Json.
-
-
-
-
Model Serialization
-
-
public class User
-{
- public UUID Id { get; set; }
- public string Name { get; set; }
-}
-
-var user = new User
-{
- Id = UUID.New(),
- Name = "John Doe"
-};
-
-// Serialize model
-string json = JsonSerializer.Serialize(user, options);
-
-// Deserialize model
-User deserializedUser = JsonSerializer.Deserialize(json, options);
-
-
Example of using UUIDs in model classes with System.Text.Json serialization.
Example of serializing and deserializing arrays of UUIDs using Newtonsoft.Json.
-
-
-
-
Model Serialization
-
-
public class User
-{
- public UUID Id { get; set; }
- public string Name { get; set; }
-}
-
-var user = new User
-{
- Id = UUID.New(),
- Name = "John Doe"
-};
-
-// Serialize model
-string json = JsonConvert.SerializeObject(user, settings);
-
-// Deserialize model
-User deserializedUser = JsonConvert.DeserializeObject(json, settings);
-
-
Example of using UUIDs in model classes with Newtonsoft.Json serialization.
-
-
-
-
-
Advanced Examples
-
-
-
Custom Model with UUID List
-
-
public class Team
-{
- public string Name { get; set; }
- public List MemberIds { get; set; }
-}
-
-var team = new Team
-{
- Name = "Development Team",
- MemberIds = new List
- {
- UUID.New(),
- UUID.New()
- }
-};
-
-// System.Text.Json
-string json = JsonSerializer.Serialize(team, options);
-Team deserializedTeam = JsonSerializer.Deserialize(json, options);
-
-// Newtonsoft.Json
-string json = JsonConvert.SerializeObject(team, settings);
-Team deserializedTeam = JsonConvert.DeserializeObject(json, settings);
-
-
Example of serializing a model containing a list of UUIDs.