CSharp - Essential Types Guid Struct


Guid struct represents a globally unique identifier: a 16-byte value.

Guids are often used for keys of various applications and databases.

The static Guid.NewGuid method generates a unique Guid:

Guid g = Guid.NewGuid ();
Console.WriteLine (g.ToString());

To instantiate an existing value, use one of the constructors. The two most useful constructors are:

public Guid (byte[] b);    // Accepts a 16-byte array
public Guid (string g);    // Accepts a formatted string

When represented as a string, a Guid is formatted as a 32-digit hexadecimal number, with optional hyphens after the 8th, 12th, 16th, and 20th digits.

The whole string can be optionally wrapped in brackets or braces:

Guid g1 = new Guid ("{0d57619c-1d6e-1847-17cb-1e2fc25081fe}");
Guid g2 = new Guid  ("0d57619c1d6e184717cb1e2fc25081fe");
Console.WriteLine (g1 == g2);  // True

ToByteArray method converts a Guid to a byte array.

static Guid.Empty property returns an empty Guid with all zeros, which is used in place of null.


using System;
class MainClass//from w  ww .  j  av  a 2 s  .com
   public static void Main(string[] args)
        Guid g = Guid.NewGuid ();
        Console.WriteLine (g.ToString());