How to work with GUIDs in C# 8

Take advantage of GUIDs to create universally unique identifiers and avoid data collisions in your applications

How to work with GUIDs in C# 8
Thinkstock

When working in applications you might often need to use Globally Unique Identifiers (GUIDs). Unique identifiers like primary keys in a SQL database ensure that important objects like customers and invoices are not duplicated or overwritten. Without unique identifiers, we could not prevent data loss or ensure the data integrity of our applications. 

A Globally Unique Identifier or GUID represents a gigantic identification number — a number so large that it is mathematically guaranteed to be unique not only in a single system like a database, but across multiple systems or distributed applications. This article discusses why we need GUIDs and how we can work with GUIDs in C# 8.0.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here

Create a console application project in Visual Studio

First off, let’s create a .NET Core Console Application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core Console Application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project to work with GUIDs in the subsequent sections of this article. Note that we’ll be using C# 8 here, so you may want to update the language version in your project.

Why do we need GUIDs?

Imagine that you have a point-of-sale application that is available in both online and offline modes on your mobile application. Assume that your application provides ID numbers that are automatically generated starting from 1. How can you merge the offline data when the connectivity is restored? What if your ID numbers have been generated in both modes? There can be collisions, right? How would you handle duplicate ID numbers? You could definitely handle this but you would have to write a lot of code — which is not what you want to do.

Here is where GUIDs come to the rescue. A GUID is a gigantic number — 128 bits long — and is almost unique. Why almost unique? Why can we not say it is unique? Basically, the number of possible GUIDs is so large that the chances of collision are extremely minimal. Nevertheless, the chances of collision are not zero. 

You can take advantage of GUIDs by making them the primary keys for your database tables. Using GUIDs will even help you to avoid merge conflicts when you are merging two or more databases. Another advantage of GUIDs is that you can generate them offline — you don’t need to be connected to the network or internet.

How are GUIDs represented?

The following is an example of a GUID. Note that a GUID is usually 128 bits long and is represented in hexadecimal.

eaa24756-3fac-4e46-b4bb-074ff4f5b846

A GUID is organized as a well-defined sequence of 32 hexadecimal digits grouped into chunks of 8-4-4-4-12. Hence you can have a maximum of 2^128 GUIDs.

Create a GUID in C# 8

In this section we’ll learn how we can work with GUIDs in C#. You can create GUIDs in .NET using the Guid struct available as part of the System namespace. Here is the easiest way to generate a GUID in C#. Write the following code in the Main() method of the Program.cs file in the project you created earlier.

Guid obj = Guid.NewGuid();
Console.WriteLine("The newly created Guid is: " + obj.ToString());
Console.ReadKey();

Create an empty GUID in C# 8

Since Guid is a struct, it is a value type and hence you cannot set it to null. To create empty Guids you can write the following code.

Guid id = new Guid();
if(id == Guid.Empty)
Console.WriteLine("The Guid is empty");

A Guid.Empty has a value of 00000000-0000-0000-0000-000000000000. You can take advantage of an empty GUID to compare it with another GUID object to determine if it is non-zero. The following code snippet illustrates this. 

if (guid != Guid.Empty){  
  //The GUID object contains non-zero values
}
else
{
  //The GUID object is empty

Here is a simple extension method that determines if a GUID is Guid.Empty. 

public static bool IsNullOrEmpty(this Guid guid)
{
  return (guid == Guid.Empty);

You can even check if your nullable GUID is null using the following extension method. 

public static bool IsNullOrEmpty(this Guid? guid)
{
  if (guid.HasValue)
    if (guid == default(Guid))
        return true;
    return false;
}

Note that default(Guid) is the same as Guid.Empty.

Convert a GUID to a string in C# 8

You can even convert a GUID to a string. The following code snippet shows how you can convert an empty GUID to a string.

string str = Guid.Empty.ToString();
Console.WriteLine(str);

Note that there is one major caveat for using GUIDs: You might have collisions. Note too that GUIDs take up some space and they are not generated in sequential order. However, you can make your GUIDs unique programmatically by using a 128-bit integer that can be represented using two ULong values and incrementing it sequentially. 

You might want to convert a GUID to a string often in your applications. You might need to do this to bind GUID data to your data controls or to pass the GUID to the user interface. You might even want to convert a GUID object to a string to format the GUID data as per your requirements.

You can create GUIDs in several different ways. These include random, time-based, hardware-based, and content-based (i.e., based on a MD5 or SHA-1 hashed value of a piece of data). I will walk you through all of these ways and other advanced features of GUIDs in a future article here.

How to do more in C#

Copyright © 2020 IDG Communications, Inc.

How to choose a low-code development platform