In this tutorial, we will cover the methods and techniques that you can use to generate the GUID values using a C# application.
C# GUID Class
Working with GUID values in C# is extremely simple and intuitive, thanks to the “Guid” class that provides us with methods and properties to work with GUID values.
Example 1: Generating a GUID Value
Hence, to generate a GUID value in a C# application, we can simply call the “NewGuid” method from the “Guid” class as shown in the following example code:
class Program
{
static void Main()
{
Guid newGuid = Guid.NewGuid();
Console.WriteLine(newGuid);
}
}
Output:
In this example, we invoke the Guid.NewGuid() method to generate a new GUID value and print it to the console.
Example 2: GUID as Object Identifier
You might come across instances where we need to give a unique identifier for a given object of a class. This is useful when each object requires a unique identifier. In such as case, we can implement it in the class as follows:
class Car
{
public Guid Id { get; private set; }
public string Model { get; set; }
public Car(string model)
{
Id = Guid.NewGuid();
Model = model;
}
}
class Program
{
static void Main()
{
Car car = new Car("Ferrari");
Console.WriteLine($"ID: {car.Id}, Name: {car.Model}");
}
}
In this case, each “Car” object has a unique ID when created, thanks to the “ID” property in the “Car” class.
An example output is as follows:
Example 3: Formatting GUID Values
We can use the Guid.ToString() method to format a GUID value according to various formats. The following shows the syntax of the method:
The format refers to a single format specifier which indicates how to format the value of the GUID. The supported parameters include “N”, “D”, “B”, “P”, or “X”. If the format value is null or an empty string, the function uses the “D” formatting.
Examples are as follows:
class Program
{
static void Main()
{
Guid newGuid = Guid.NewGuid();
Console.WriteLine("N format: " + newGuid.ToString("N"));
Console.WriteLine("D format: " + newGuid.ToString("D"));
Console.WriteLine("B format: " + newGuid.ToString("B"));
Console.WriteLine("P format: " + newGuid.ToString("P"));
Console.WriteLine("X format: " + newGuid.ToString("X"));
}
}
The resulting output is as follows:
D format: d975cf98-5ce0-4d4b-837a-dca3e950800d
B format: {d975cf98-5ce0-4d4b-837a-dca3e950800d}
P format: (d975cf98-5ce0-4d4b-837a-dca3e950800d)
X format: {0xd975cf98,0x5ce0,0x4d4b,{0x83,0x7a,0xdc,0xa3,0xe9,0x50,0x80,0x0d}}
Conclusion
In this tutorial, you learned how to create and work with GUID values in a C# application to generate unique identifier values for a specific entity. You can reference the docs for more details on the “Guid” class.