Basic GUID Operations in C#.Net & VB.NET

Understanding of basic guid operation in c#.net and VB.net. We cover Generate New GUID, Parse String To GUID, Comparing GUID, Empty GUID Generation.
In today's article I will show you the What is GUID and what are different ways to use and real-life example using C#.net and VB.NET.  Guid is a 128-bitcombination of number and characters.  Guid can be used as unique key in database, as a file name and identifier. So here we will user .net core 10 and a console application. So, for this article first we will create a new .net core 10 console application. 

GUID Operations

Generate New GUID

C#.Net

Guid guid = Guid.NewGuid();
Console.WriteLine("Generated New GUID: " + guid); 

VB.NET

Dim guid As Guid = Guid.NewGuid()
Console.WriteLine("Generated New GUID: " & guid.ToString()) 
In above code i have used Guid.NewGuid() to generate the new GUID. After generation of GUID i have printed it by converting it into string.  Now let's run the code to check the output.

Generate New GUID

Convert or Parse String To GUID

C#.Net

string strGuid = "1384134c-2f0d-4b52-a9a6-8c2b2e3ecbf0";
Console.WriteLine("Original GUID String: " + strGuid);
Guid guid = Guid.Parse(strGuid);
Console.WriteLine("Parsed GUID: " + guid.ToString()); 

VB.NET

Dim strGuid As String = "1384134c-2f0d-4b52-a9a6-8c2b2e3ecbf0"
Console.WriteLine("Original GUID String: " & strGuid)
Dim guid As Guid = Guid.Parse(strGuid)
Console.WriteLine("Parsed GUID: " & guid.ToString()) 
In above code I have taken a string variable and in this I have added a guid string value. Now to parse the string to Guid I have used Guid.Parse(). Guid.Parse() you use in a scenario where to sure that the parsed string is a valid guid string. Otherwise use Guid.TryParse(). Now let's run the code to check the output.

Convert or Parse String To GUID

Comparing GUID

C#.Net

Guid guid1 = Guid.NewGuid();
Guid guid2 = Guid.NewGuid();
bool status= guid1.Equals(guid2);
Console.WriteLine("Is both guid same: " + status); 

VB.NET

Dim guid1 As Guid = Guid.NewGuid()
Dim guid2 As Guid = Guid.NewGuid()
Dim status As Boolean = guid1.Equals(guid2)
Console.WriteLine("Is both guid same: " & status) 
In above code I have taken two guid and used Equal() method to compare one guid to another one. If the guid, are we will get true otherwise will get false. 

Comparing GUID

Empty GUID Generation

C#.Net

Guid emptyGuid = Guid.Empty;
Console.WriteLine("Generated Empty GUID: " + emptyGuid); 
VB.NET
Dim emptyGuid As Guid = Guid.Empty
Console.WriteLine("Generated Empty GUID: " & emptyGuid.ToString()) 
To generate the empty guid Udemy have been used. 

Empty GUID

Post a Comment