BlackWaspTM
.NET Framework
.NET 1.1+

Creating Globally Unique Identifiers (GUIDs) in .NET (2)

It is important in many business systems that items are marked with a unique reference. Often this is a sequential number generated by a database or a code entered by a user. In some situations, these options are not enough so GUIDs may be employed.

Generating New Guids

The Guid constructors are useful when a specific GUID value is required. However, when new objects are created and require a new unique identifier, a new Guid value must be generated. This is achieved using the static NewGuid method, as demonstrated by the following example. NB: The GUID generated will not match the one shown in the sample code.

Guid id = Guid.NewGuid();
Console.WriteLine(id);          // Outputs "8c1d1c4b-df68-454c-bf30-953e5701949f"

Empty Guids

As the Guid structure cannot be set to null, a value must be used to represent an ID that is not set. This value, known as the empty GUID, consists only of zeroes. This is the same value that is generated by the parameter-less constructor. In order that a new Guid structure is not created every time a value must be compared with the empty GUID, the structure provides the Empty property. This property is read-only and always returns an empty GUID.

Guid id = Guid.NewGuid();
Guid id2 = new Guid();

Console.WriteLine(id == Guid.Empty);    // Outputs "False"
Console.WriteLine(id2 == Guid.Empty);   // Outputs "True"

Console.WriteLine(Guid.Empty);  // Outputs "00000000-0000-0000-0000-000000000000"

Formatting Guids as Strings

As with all objects and structures, the Guid can be converted to a string using the ToString method. If the method is used without parameters, the Guid is formatted as a simple series of hexadecimal digits in the five groups described earlier.

string s = Guid.Empty.ToString();
Console.WriteLine(s);           // Outputs "00000000-0000-0000-0000-000000000000"

The format of the converted string can be modified using a format specifier. This is passed as a string parameter to the ToString method. The four available format specifiers are listed in the table below.

SpecifierDescriptionExamples
DDefault format of thirty-two digits with groups separated by hyphens."00000000-0000-0000-0000-000000000000"
NA series of thirty-two hexadecimal digits with no separators between groups."00000000000000000000000000000000"
BDefault format surrounded by brackets."{00000000-0000-0000-0000-000000000000}"
PDefault format surrounded by parentheses."(00000000-0000-0000-0000-000000000000)"

These formats can be demonstrated by executing the following sample code:

Console.WriteLine(Guid.Empty.ToString("D"));
Console.WriteLine(Guid.Empty.ToString("N"));
Console.WriteLine(Guid.Empty.ToString("B"));
Console.WriteLine(Guid.Empty.ToString("P"));

/* OUTPUT

00000000-0000-0000-0000-000000000000
00000000000000000000000000000000
{00000000-0000-0000-0000-000000000000}
(00000000-0000-0000-0000-000000000000)

*/
2 December 2007