Is there a difference when you generate a GUID using NewGuid();
vs System.Guid.NewGuid().ToString("D");
or they are the same thing?
Guid. NewGuid(). ToString() is string representation of GUID, i.e. returns string object, while Guid. NewGuid() returns Guid datatype.
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.
ToString("D") is that it allows you to specify the preceding number of digits. e.g, var i = 123; var stringed = i.ToString("D5");//stringed = 00123.
The Parse method trims any leading or trailing white space from input and converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table.
I realize that this question already has an accepted answer, but I thought it would be useful to share some information about formatting guids.
The ToString() (no parameters) method formats a guid using this format:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
The ToString(string format) method formats a guid in one of several ways:
"N" - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (32 digits) "D" - xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (32 digits separated by hyphens) "B" - {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} (same as "D" with addition of braces) "P" - (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) (same as "D" with addition of parentheses) "X" - {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}
Calling Guid.ToString("D")
yields the same result as calling Guid.ToString()
.
As mentioned in the other answers, the guid itself has no format. It is just a value. Note, that you can create guids using NewGuid or using the guid's constructor. Using NewGuid, you have no control over the value of the guid. Using the guid's constructor, you can control the value. Using the constructor is useful if you already have a string representation of a guid (maybe you read it from a database) or if you want to make it easier to interpret a guid during development. You can also use the Parse, ParseExact, TryParse, and TryParseExact methods.
So, you can create guids like this:
Guid g1 = Guid.NewGuid(); //Get a Guid without any control over the contents Guid g2 = new Guid(new string('A',32)); //Get a Guid where all digits == 'A' Guid g3 = Guid.Parse(g1.ToString()); Guid g4 = Guid.ParseExact(g1.ToString("D"),"D"); Guid g5; bool b1 = Guid.TryParse(g1.ToString(), out g5); Guid g6; bool b2 = Guid.TryParseExact(g1.ToString("D"),"D", out g6);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With