Generate UUIDs in C#

Resources  |  Generate UUIDs in C#

In C#, generating a UUID (Universally Unique Identifier) is straightforward, thanks to the built-in Guid structure provided by the .NET framework. Below are examples showing how to generate a UUID in C#:

Basic UUID Generation

To generate a UUID, you can use the Guid.NewGuid() method, which creates a new GUID (which is Microsoft's implementation of a UUID):

using System;

class Program
{
    static void Main()
    {
        // Generate a new UUID (GUID)
        Guid newUuid = Guid.NewGuid();

        // Output the generated UUID
        Console.WriteLine("Generated UUID: " + newUuid.ToString());
    }
}

Running the Code

  1. Create a new C# console application using your preferred development environment (e.g., Visual Studio, Visual Studio Code).
  2. Copy and paste the code above into the Program.cs file.
  3. Run the application to see the generated UUID printed to the console.

Explanation

  • Guid.NewGuid(): This method generates a new GUID, which is a 128-bit integer (16 bytes) that can be used to uniquely identify information.
  • newUuid.ToString(): Converts the GUID to its string representation in the standard format (e.g., xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).

Output Example

When you run the code, the output will be similar to:

Generated UUID: 123e4567-e89b-12d3-a456-426614174000

Each time you run the program, a different UUID will be generated.

Additional Formatting

If you need the UUID in a specific format, you can use different format specifiers with the ToString() method:

Guid newUuid = Guid.NewGuid();

// Default format
Console.WriteLine("Default: " + newUuid.ToString());

// No hyphens
Console.WriteLine("N format: " + newUuid.ToString("N"));

// Hyphens, no braces
Console.WriteLine("D format: " + newUuid.ToString("D"));

// Hyphens, braces
Console.WriteLine("B format: " + newUuid.ToString("B"));

// Hyphens, parentheses
Console.WriteLine("P format: " + newUuid.ToString("P"));

Format Specifiers

  • "N": 32 digits, no hyphens (e.g., 123e4567e89b12d3a456426614174000)
  • "D": 32 digits separated by hyphens (e.g., 123e4567-e89b-12d3-a456-426614174000)
  • "B": 32 digits separated by hyphens, enclosed in braces (e.g., {123e4567-e89b-12d3-a456-426614174000})
  • "P": 32 digits separated by hyphens, enclosed in parentheses (e.g., (123e4567-e89b-12d3-a456-426614174000))

This flexibility allows you to use the UUID in the format that best suits your application's needs.