Is there a difference when you generate a GUID using NewGuid();
vs System.Guid.NewGuid().ToString(\"D\");
or they are the same thing?
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);
Guid.NewGuid().ToString()
is string representation of GUID, i.e. returns string
object, while Guid.NewGuid()
returns Guid
datatype.
Using System.Guid.NewGuid()
you will get a object of Guid
type
Using System.Guid.NewGuid().ToString("D");
you will get the string representation of Guid
object
Also as I know no difference between .ToString("D")
and .ToString()
The generation algorithm has to be the same for both, because System.Guid.NewGuid().ToString("D")
is calling System.Guid.NewGuid()
, and then calling ToString
on the result, i.e., both of your examples are calling the same method to generate the guid. As to comparing the "format" - this does not make sense because System.Guid.NewGuid()
does not have a "format" in the same way as System.Guid.NewGuid().ToString("D")
- it is only by calling the ToString
method that you give the internal representation of the guid an external, string format. The format the string takes will depend on the argument you pass to the string method.