Question

Consider the following code.

var guid = Guid.NewGuid();
var a = guid.ToString();
var b = guid.ToString("N");

The value of a looks like 7c9e6679-7425-40de-944b-e07fc1f90ae7.
The value of b looks like 7c9e6679742540de944be07fc1f90ae7.

Is there a way to tell .NET that I want the second form, with format string N, by default?

Default behaviors for ToString on other types, such as DateTime, are tied to the current culture. Is the default behavior for Guid possibly tied to the culture in a similar way? (I'm doubtful.)

For compatibility reasons, I need GUID string representations without dashes to be the norm throughout my codebase, but it's very easy to forget the N parameter without any warning.

Was it helpful?

Solution

No. The documentation on this is clear:

Returns a string representation of the value of this instance in registry format.

And

Return Value
Type: System.String
The value of this Guid, formatted by using the "D" format specifier as follows:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

ToString() for some other objects consults the locale formatter, but not Guid unfortunately.

You could define an extension method for Guid and use that instead:

public static class GuidExtensions
{
    public static string ToMyString(this Guid guid)
    {
        return guid.ToString("N");
    }
}

// elsewhere
Guid guid = /* ... */;
Console.WriteLine(guid.ToMyString());

But I suppose forgetting to call this would be just as easy as forgetting the "N" so this may not be much of an improvement. (If you do go this route anyway, please think of a better name for the extension method than ToMyString() :-))

OTHER TIPS

Is there a way to tell .NET that I want the second form, with format string N, by default?

No, that's the default behavior of Guid.ToString().

The value of this Guid, formatted by using the "D" format specifier as follows: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where the value of the GUID is represented as a series of lowercase hexadecimal digits in groups of 8, 4, 4, 4, and 12 digits and separated by hyphens. An example of a return value is "382c74c3-721d-4f34-80e5-57657b6cbc27". To convert the hexadecimal digits from a through f to uppercase, call the String.ToUpper method on the returned string.

You could add a custom FxCop rule (or customize some other static analysis tool) to detect usage of Guid.ToString() but you can't prevent it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top