Take advantage of GUIDs to create universally unique identifiers and avoid data collisions in your applications Credit: 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. 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# When to use an abstract class vs. interface in C# How to work with AutoMapper in C# How to use lambda expressions in C# How to work with Action, Func, and Predicate delegates in C# How to work with delegates in C# How to implement a simple logger in C# How to work with attributes in C# How to work with log4net in C# How to implement the repository design pattern in C# How to work with reflection in C# How to work with filesystemwatcher in C# How to perform lazy initialization in C# How to work with MSMQ in C# How to work with extension methods in C# How to us lambda expressions in C# When to use the volatile keyword in C# How to use the yield keyword in C# How to implement polymorphism in C# How to build your own task scheduler in C# How to work with RabbitMQ in C# How to work with a tuple in C# Exploring virtual and abstract methods in C# Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos