Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guid.NewGuid() vs. new Guid()

Tags:

c#

guid

What's the difference between Guid.NewGuid() and new Guid()?

Which one is preferred?

like image 282
OscarRyz Avatar asked Aug 13 '12 16:08

OscarRyz


People also ask

What does GUID NewGuid () do?

Guid. NewGuid() creates an empty Guid object, initializes it by calling CoCreateGuid and returns the object.

Is GUID NewGuid thread safe?

You are concerned with concurrency: fortunately, the NewGuid method is thread-safe, which means it either locks or utilizes a thread-static random number generator for its purposes.

How do you define a new GUID?

GUIDs are most commonly written in text as a sequence of hexadecimal digits as such, 3F2504E0-4F89-11D3-9A0C-0305E82C3301. Often braces are added to enclose the above format, as such: {3F2504E0-4F89-11D3-9A0C-0305E82C3301}

How do I generate a new GUID?

To Generate a GUID in Windows 10 with PowerShell, Type or copy-paste the following command: [guid]::NewGuid() . This will produce a new GUID in the output. Alternatively, you can run the command '{'+[guid]::NewGuid(). ToString()+'}' to get a new GUID in the traditional Registry format.


2 Answers

new Guid() makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).

Guid.NewGuid() makes an actual guid with a unique value, what you probably want.

like image 120
MarkPflug Avatar answered Oct 01 '22 12:10

MarkPflug


Guid.NewGuid() creates a new UUID using an algorithm that is designed to make collisions very, very unlikely.

new Guid() creates a UUID that is all-zeros.

Generally you would prefer the former, because that's the point of a UUID (unless you're receiving it from somewhere else of course).

There are cases where you do indeed want an all-zero UUID, but in this case Guid.Empty or default(Guid) is clearer about your intent, and there's less chance of someone reading it expecting a unique value had been created.

In all, new Guid() isn't that useful due to this lack of clarity, but it's not possible to have a value-type that doesn't have a parameterless constructor that returns an all-zeros-and-nulls value.

Edit: Actually, it is possible to have a parameterless constructor on a value type that doesn't set everything to zero and null, but you can't do it in C#, and the rules about when it will be called and when there will just be an all-zero struct created are confusing, so it's not a good idea anyway.

like image 36
Jon Hanna Avatar answered Oct 01 '22 12:10

Jon Hanna