How to Generate GUIDs in C#
Learn how to generate GUIDs in C# with practical examples for GUID v4 and GUID v7.
Convert a string to a GUID in C# with Guid.Parse or Guid.TryParse, and convert a GUID back to a string with ToString() when you need standard or compact formatting.
Guid.TryParse for untrusted input, and use guid.ToString("D") unless you have a specific integration format requirement.Use Guid.Parse() when the input is guaranteed to be valid, or Guid.TryParse() when you want to avoid exceptions.
using System;
string input = "550e8400-e29b-41d4-a716-446655440000";
Guid parsed = Guid.Parse(input);
Console.WriteLine(parsed);
if (Guid.TryParse(input, out Guid safeParsed))
{
Console.WriteLine($"Parsed safely: {safeParsed}");
}Guid.ToString() supports multiple format specifiers depending on what another system expects.
using System;
Guid id = Guid.Parse("550e8400-e29b-41d4-a716-446655440000");
Console.WriteLine(id.ToString()); // D: 550e8400-e29b-41d4-a716-446655440000
Console.WriteLine(id.ToString("N")); // N: 550e8400e29b41d4a716446655440000
Console.WriteLine(id.ToString("B")); // B: {550e8400-e29b-41d4-a716-446655440000}
Console.WriteLine(id.ToString("P")); // P: (550e8400-e29b-41d4-a716-446655440000)
Console.WriteLine(id.ToString("X")); // X: {0x550e8400,0xe29b,0x41d4,{0xa7,0x16,0x44,0x66,0x55,0x44,0x00,0x00}}ToString() format is D, which includes hyphens.N is useful when another system expects 32 hexadecimal characters without dashes.TryParse is the safer choice for API input, config values, and user-entered data.Guid.Parse() only when invalid input should be treated as a bug. Use Guid.TryParse() for external input so you can handle invalid values without throwing an exception.D: 32 hexadecimal digits separated by hyphens, such as 550e8400-e29b-41d4-a716-446655440000.These articles expand on related concepts, formats and practical considerations.