What is the default value for Guid?

201.5k views Asked by At

The default value for int is 0 , for string is "" and for boolean it is false. Could someone please clarify what the default value for guid is?

5

There are 5 answers

2
David Watts On

The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)

This can be invoked using Guid.Empty or new Guid()

If you want a new GUID, you use Guid.NewGuid()

0
Hamid Pourjam On

You can use Guid.Empty. It is a read-only instance of the Guid structure with the value of 00000000-0000-0000-0000-000000000000

you can also use these instead

var g = new Guid();
var g = default(Guid);

beware not to use Guid.NewGuid() because it will generate a new Guid.

use one of the options above which you and your team think it is more readable and stick to it. Do not mix different options across the code. I think the Guid.Empty is the best one since new Guid() might make us think it is generating a new guid and some may not know what is the value of default(Guid).

2
Peter Rasmussen On

You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - "00000000-0000-0000-0000-000000000000".

new Guid()

default(Guid)

Guid.Empty

As Use Keim points out in the comments default is short for default(Guid)

4
THE LIFE-TIME LEARNER On

You can create an Empty Guid or New Guid using a class.

The default value of Guid is 00000000-0000-0000-0000-000000000000

public class clsGuid  // This is a class name
{
    public Guid MyGuid { get; set; }
}

static void Main(string[] args)
{
    clsGuid cs = new clsGuid();   
    Console.WriteLine(cs.MyGuid); // This will give empty Guid "00000000-0000-0000-0000-000000000000"

    cs.MyGuid = new Guid();
    Console.WriteLine(cs.MyGuid); // This will also give empty Guid "00000000-0000-0000-0000-000000000000"

    cs.MyGuid = Guid.NewGuid();
    Console.WriteLine(cs.MyGuid); // This way, it will give a new Guid (eg. "d94828f8-7fa0-4dd0-bf91-49d81d5646af")

    Console.ReadKey(); // This line holds the output screen in a console application
}
0
tinamou On

To extend answers above, you cannot use Guid default value with Guid.Empty as an optional argument in method, indexer or delegate definition, because it will give you compile time error. Use default(Guid) or new Guid() instead.