How GUID Is Generated In C#

Normally, we use GUID for uniqueness in the project. Before we start, let us learn about GUID - what it is and how to create it. If you know these answers, do you ever wonder how it's actually created?
 
So, first, let's start with what GUID is.
 
GUID stands for Globally Unique Identifier or UUID which stands for Universally Unique Identifier. Normally, Microsoft technology developers work with GUID and REST developers work with UUID. 16 bytes (128 bits) is acceptable for uniqueness.
 

How to create GUID?

 
You can create GUID by using the below line.
  1. var guid = Guid.NewGuid(); 
There are many methods for GUID which you can use as per your need.
 
How GUID Is Generated 
 
The main part is how GUID is generated.
 
If you notice the GUID, it is a combination of four parts -  70122D63-6FB3-E911-8369-ABBAE7037764,
 
Let's break down GUID in four parts to understand.
  • First 60 bits (7.5 Bytes) of timestamp
  • Second 48 bits (6 Bytes) of computer identifier,
  • Third 14 bits (1.75 Bytes) of uniquifier
  • Last 6 bits (0.75 Bytes) are fixed,
Total Bits = 60 + 48 + 14 + 6  = 128 Bits
Or
Total Bytes = 7.5 + 6 + 1.75 + 0.75 = 16 Bytes
 
There are many GUID generation algorithms. All algorithms are designed in a way that won't generate the same GUID twice, but here is another question -- are GUIDs are 100% unique?. The answer is no, there is no guarantee of uniqueness, but there is a rare and very small chance of the same GUID being generated twice in the next fifty billion trillion years. For example, just assume the sea, which has 7 * 1022 fishes, every fish could have 8.8×1015 universally unique GUIDs.
 
There are some key points which we should keep in mind,
  • Don't use GUID as random numbers.
  • Don't split GUID in half or any part, otherwise, it will lose uniqueness.
  • There are lots of algorithms to generate GUID.
  • We can not prevent a user from using an earlier generated GUID which can create collision if we don't set up that column as a primary key.
  • Each GUID occupies 16 bytes, which occupies more space if you have millions of records.
  • We should ignore GUID for a small project, because of its effects on database performance.
I hope you guys found something useful, please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.
 
Here is another useful reading on GUIDs, What is GUID in C#.