89

This Code:

Something = new Guid() 

is returning:

00000000-0000-0000-0000-000000000000

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

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
Ante
  • 8,567
  • 17
  • 58
  • 70
  • Possible duplicate of [C# how to create a Guid value?](http://stackoverflow.com/questions/2344098/c-sharp-how-to-create-a-guid-value) – StayOnTarget May 09 '17 at 13:52

5 Answers5

149

You should use Guid.NewGuid()

Randolpho
  • 55,384
  • 17
  • 145
  • 179
Will Dean
  • 39,055
  • 11
  • 90
  • 118
61

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.

Josh
  • 68,005
  • 14
  • 144
  • 156
12

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();
DOK
  • 32,337
  • 7
  • 60
  • 92
  • Yes, it should be there (http://msdn.microsoft.com/en-us/library/system.guid_members.aspx) but I can't use it. Why? – Ante May 24 '09 at 16:06
  • "I can't use it" - what happens when you try to use it? Type it out manually (perhaps there's an issue with your intellisense) and try to compile - do you get compilation errors? – Matt Brindley May 24 '09 at 16:14
  • What do you mean when you say you "can't use it"? If you type Guid x = System.Guid.NewGuid() and compile, do you get an error? Or do you not like the value you're getting for x? – DOK May 24 '09 at 16:17
  • LOL yea that Guid algorithm sometimes needs a fresh reboot. Sigh. – Josh Jul 21 '11 at 21:42
4

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

Use Guid.NewGuid(); instead

Kaushik
  • 2,072
  • 1
  • 23
  • 31
Will Yu
  • 546
  • 5
  • 12
3
 Guid g1 = Guid.NewGuid();

 string s1;
 s1 = g1.ToString();
 Console.WriteLine("{0}",s1);
 Console.ReadKey();
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Leo
  • 399
  • 4
  • 6