How to use Guids in C#?

C#Guid

C# Problem Overview


This Code:

Something = new Guid() 

is returning:

> 00000000-0000-0000-0000-000000000000

all the time and I can't tell why? So, why?

C# Solutions


Solution 1 - C#

You should use Guid.NewGuid()

Solution 2 - C#

Just a quick explanation for why you need to call NewGuid as opposed to using the default constructor... In .NET all structures (value types like int, decimal, Guid, DateTime, etc) must have a default parameterless constructor that initializes all of the fields to their default value. In the case of Guid, the bytes that make up the Guid are all zero. Rather than making a special case for Guid or making it a class, they use the NewGuid method to generate a new "random" Guid.

Solution 3 - C#

It's in System.Guid.

To dynamically create a GUID in code:

Guid messageId = System.Guid.NewGuid();

To see its value:

string x = messageId.ToString();

Solution 4 - C#

something = new Guid() equals something = Guid.Empty.

Use Guid.NewGuid(); instead

Solution 5 - C#

 Guid g1 = Guid.NewGuid();

 string s1;
 s1 = g1.ToString();
 Console.WriteLine("{0}",s1);
 Console.ReadKey();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnteView Question on Stackoverflow
Solution 1 - C#Will DeanView Answer on Stackoverflow
Solution 2 - C#JoshView Answer on Stackoverflow
Solution 3 - C#DOKView Answer on Stackoverflow
Solution 4 - C#Will YuView Answer on Stackoverflow
Solution 5 - C#LeoView Answer on Stackoverflow