Interesting Quirk when Formatting Guid’s as Strings….

Originally posted by Nick Heppleston at: http://www.modhul.com/2009/03/19/interesting-quirk-when-formatting-guids-as-strings/

I noticed an interesting quirk last night while trying to format a Guid into a string representation – by default, Guid.ToString() does not return an accurate representation of a GUID with curly braces. Hmmmmmm…..

Consider the following simple test, here we are instantiating a new Guid and before outputting the value to the debugger, we capture its value – note the curly braces at the end of the Guid:

guidcontainscurlybraces

If we let the test run its course, we get the Guid formatted as a string (using the default formatter) written to the debugger, but there are no curly braces:

defaulttostringformatterstripsguidcurlybraces

After much head scratching and Googling, I decided to look at the MSDN documentation for the Guid.ToString() method – low and behold there are several format specifiers that can be provided to the ToString() method which determine the formatting provided to the resultant string. Using the format specifiers:

testguiddottostringformatspecifiers

we get the desired output:

testguiddottostringformatspecifierstrace

If no format specifier is used (i.e. we just Guid.ToString()), the default format is ‘D’ – no braces.

Advertisements

5 thoughts on “Interesting Quirk when Formatting Guid’s as Strings….

  1. LK, I don’t know if this is a spam comment or not… I’d be much more inclined to take your comment onboard if I knew who was making such an insightful contribution.

    Care to identify yourself?

    Nick.

  2. This isn’t a “Quirk” — when in the debugger, it knows that a GUID is a structure and the standard “structure value formatter” that displays the tooltip builds “[struct name] ‘{‘ [instance.ToString()] ‘}'” so you get the ‘{}’; Your “Trace.WriteLine” doesn’t included this additional formatting so you don’t see them…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s