System.Guid is used quite often by .NET developers. For most of the scenarios that you encounter it works quite well. However consider the following code block:
string guidstr1 = "122F5113-FF7E-455D-8FF0-D79A2B830375";
string guidstr2 = "076e6c09-57b1-48da-836f-57d3646d8cb0";
Guid guid = Guid.NewGuid();
Console.WriteLine(guid);
guid = new Guid(guidstr1);
Console.WriteLine(guid);
guid = new Guid(guidstr2);
Console.WriteLine(guid);
Console.ReadLine();
Output:
edca0d0e-e62f-4c03-b41a-16cc9176df71
122f5113-ff7e-455d-8ff0-d79a2b830375
076e6c09-57b1-48da-836f-57d3646d8cb0
There are many styles supported for GUID but there is no option that can preserve casing of the value.
string guidstr1 = "122F5113-FF7E-455D-8FF0-D79A2B830375";
string guidstr2 = "076e6c09-57b1-48da-836f-57d3646d8cb0";
Guid guid = Guid.NewGuid();
Console.WriteLine(guid);
guid = new Guid(guidstr1);
Console.WriteLine(guid);
guid = new Guid(guidstr2);
Console.WriteLine(guid);
Console.ReadLine();
Output:
edca0d0e-e62f-4c03-b41a-16cc9176df71
122f5113-ff7e-455d-8ff0-d79a2b830375
076e6c09-57b1-48da-836f-57d3646d8cb0
Did you expect the highlighted output? Parsed GUID has changed the casing of alphabets.
If you crack open ILSpy and checkout the implementation of Guid constructor, you can locate the line that tries to parse the Guid using a style option "any".
public Guid(string g)
{
if (g == null)
{
throw new ArgumentNullException("g");
}
this = Guid.Empty;
Guid.GuidResult guidResult = default(Guid.GuidResult);
guidResult.Init(Guid.GuidParseThrowStyle.All);
if (Guid.TryParseGuid(g, Guid.GuidStyles.Any, ref guidResult))
{
this = guidResult.parsedGuid;
return;
}
throw guidResult.GetGuidParseException();
}
{
if (g == null)
{
throw new ArgumentNullException("g");
}
this = Guid.Empty;
Guid.GuidResult guidResult = default(Guid.GuidResult);
guidResult.Init(Guid.GuidParseThrowStyle.All);
if (Guid.TryParseGuid(g, Guid.GuidStyles.Any, ref guidResult))
{
this = guidResult.parsedGuid;
return;
}
throw guidResult.GetGuidParseException();
}
There are many styles supported for GUID but there is no option that can preserve casing of the value.
private enum GuidStyles
{
None = 0,
AllowParenthesis = 1,
AllowBraces = 2,
AllowDashes = 4,
AllowHexPrefix = 8,
RequireParenthesis = 16,
RequireBraces = 32,
RequireDashes = 64,
RequireHexPrefix = 128,
HexFormat = 160,
NumberFormat = 0,
DigitFormat = 64,
BraceFormat = 96,
ParenthesisFormat = 80,
Any = 15
}
{
None = 0,
AllowParenthesis = 1,
AllowBraces = 2,
AllowDashes = 4,
AllowHexPrefix = 8,
RequireParenthesis = 16,
RequireBraces = 32,
RequireDashes = 64,
RequireHexPrefix = 128,
HexFormat = 160,
NumberFormat = 0,
DigitFormat = 64,
BraceFormat = 96,
ParenthesisFormat = 80,
Any = 15
}
Interesting to know!!