[C#]Generating Unique Identifiers (GUID)

目次

Overview

This article explains how to generate a GUID (Globally Unique Identifier), which is used when unique values are needed, such as for database primary keys, temporary filenames, or session IDs. By using the standard .NET Guid.NewGuid() method, you can easily create a version 4 (random-based) GUID.

Specifications (Input/Output)

  • Input: None
  • Output: A randomly generated System.Guid structure.
  • String Formats:
    • No argument (“D”): 32 digits with hyphens (Standard).
    • “N”: 32 digits without hyphens.
    • “B”: Enclosed in braces {}.
    • “P”: Enclosed in parentheses ().
    • “X”: Hexadecimal structure representation.

Basic Usage

Call Guid.NewGuid() and use ToString() to treat it as a string.

// Generate a new GUID
Guid myId = Guid.NewGuid();

// Display as a string (e.g., "a9c3b8...")
Console.WriteLine(myId.ToString());

Full Code

The following console application generates a GUID and demonstrates how the output format changes based on the format specifiers passed to ToString.

using System;

class Program
{
    static void Main()
    {
        // 1. Generate a new GUID (returns a different value every time)
        Guid guid = Guid.NewGuid();

        Console.WriteLine("=== GUID Generation ===");
        
        // 2. Output in various formats
        // No argument (same as "D"): Standard hyphen-separated
        Console.WriteLine($"Default: {guid.ToString()}");

        // "D": 32 digits + hyphens (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
        Console.WriteLine($"Format D: {guid.ToString("D")}");

        // "N": 32 digits only (no hyphens)
        // Usage: Filenames, URL parameters, etc.
        Console.WriteLine($"Format N: {guid.ToString("N")}");

        // "B": With braces
        // Usage: Registry keys, etc.
        Console.WriteLine($"Format B: {guid.ToString("B")}");

        // "P": With parentheses
        Console.WriteLine($"Format P: {guid.ToString("P")}");

        // "X": Hexadecimal structure representation ({0x...,0x...,...})
        // Usage: Constant declarations within code, etc.
        Console.WriteLine($"Format X: {guid.ToString("X")}");
    }
}

Execution Result Example

=== GUID Generation ===
Default: 5f3d7b2a-9e1c-4b8d-a5f2-123456789abc
Format D: 5f3d7b2a-9e1c-4b8d-a5f2-123456789abc
Format N: 5f3d7b2a9e1c4b8da5f2123456789abc
Format B: {5f3d7b2a-9e1c-4b8d-a5f2-123456789abc}
Format P: (5f3d7b2a-9e1c-4b8d-a5f2-123456789abc)
Format X: {0x5f3d7b2a,0x9e1c,0x4b8d,{0xa5,0xf2,0x12,0x34,0x56,0x78,0x9a,0xbc}}

Customization Points

  • Empty GUID: To represent an initial value or an “unassigned ID,” use Guid.Empty instead of Guid.NewGuid(). This returns an all-zero GUID (00000000-0000-0000-0000-000000000000).
  • Converting to Specific Formats: While it is common to pass a Guid type directly to a database, the “D” (standard) or “N” (shortened) formats are frequently chosen when saving as a text column.

Points of Caution

  • Randomness (Version 4): Guid.NewGuid() typically generates a version 4 (random-based) GUID. The probability of collision is astronomically low, but it is not mathematically guaranteed to be absolutely unique.
  • Database Indexes: Using random values as a primary key (especially a clustered index) can cause data to be inserted at random locations. This leads to index fragmentation and may degrade performance. In SQL Server, the use of sequential GUIDs like NewSequentialId is often recommended.
  • Predictability: While Guid.NewGuid() is convenient for security tokens or password reset URLs, an implementation using a cryptographically secure random number generator (RandomNumberGenerator) is more robust.

Application

Restoring a GUID from a String

This example shows how to convert an ID string received from an external source back into a Guid type.

string inputId = "5f3d7b2a-9e1c-4b8d-a5f2-123456789abc";

if (Guid.TryParse(inputId, out Guid result))
{
    Console.WriteLine($"Conversion successful: {result}");
}
else
{
    Console.WriteLine("Invalid GUID format.");
}

Summary

Guid.NewGuid() is the standard way to generate unique IDs in distributed systems.

  • Format “D”: The most common and highly readable format.
  • Format “N”: Ideal for URLs or filenames where you want to avoid special symbols.
  • Database Usage: Consider the impact on index performance before adoption.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次