Generates GUID or UUID in C# examples

GUID and UUID are common unique strings and both are the same.

This tutorial explains Generating GUID in C# with examples.

How to Generate UUID in C# with example

The system namespace contains the Guid class method NewGuid method, which generates UUID string. It is unique and random.

using System;

public class Program
{
    public static void Main()
    {
    var uuid= System.Guid.NewGuid();

        Console.WriteLine(uuid); //b64b530c-ec7a-44ca-8779-8f99bd457798

    }
}

How to generate an empty UUID in C#

Empty GUiD contains all zeroes in it. Multiple ways we can generate an Empty or Blank GUID, First, use the Empty property on the Guid Class. The second way, new Guid() class returns an empty string

Here is an example

using System;

public class Program
{
    public static void Main()
    {
    var uuid= System.Guid.Empty;
    var guid = new Guid();
    Console.WriteLine(guid);
    Console.WriteLine(uuid);


    }
}

Output:

00000000-0000-0000-0000-000000000000
00000000-0000-0000-0000-000000000000

Difference between Guid.NewGuid() vs. new Guid()

Guid is a class of System namespace.

Guid.NewGuid() and new Guid() are used to generate UUID values.

Guid.NewGuid(): generates unique values,b64b530c-ec7a-44ca-8779-8f99bd457798 is an example value returned new Guid(): returns empty UUID, example value is 00000000-0000-0000-0000-000000000000

Guid.NewGuid() is useful for unique random value for UUID value.

Check if Nullable Guid is empty in c#

sometimes, We want to check given Guid is empty or not

To check empty or null values, compare using null or match the given value with the Guid.Empty property

using System;

public class Program
{
    public static void Main()
    {
    var uuid= System.Guid.Empty;
    var guid = new Guid();
    Console.WriteLine(uuid == null || uuid == Guid.Empty); // True
    Console.WriteLine(guid == null || guid == Guid.Empty);//True


    }
}