Codectionary / Developer documentation / C#

Guid Parsing and Formatting

Guid stores a 128-bit identifier. TryParse handles malformed user input without using exceptions for an expected validation outcome. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

Guid stores a 128-bit identifier. TryParse handles malformed user input without using exceptions for an expected validation outcome. Use a .NET 8+ console project; replace Program.cs with this C# example.

The D format uses hyphen-separated hexadecimal groups. The discard ignores the unusable output from the failed parse.

Syntax

Guid.TryParse(text, out Guid value); value.ToString("D")

Examples

Guid Parsing and Formatting

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
string text = "550e8400-e29b-41d4-a716-446655440000";
if (Guid.TryParse(text, out Guid id))
    Console.WriteLine(id.ToString("D"));
Console.WriteLine(Guid.TryParse("invalid", out _));
  1. Expected output: 550e8400-e29b-41d4-a716-446655440000 False
  2. The D format uses hyphen-separated hexadecimal groups. The discard ignores the unusable output from the failed parse.
  3. Use Guid.NewGuid when a fresh identifier is required.

Best practices

  • Use Guid.NewGuid when a fresh identifier is required.
  • Keep authorization checks independent of identifier generation.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading