Why Guid.TryParse allows trailing/leading spaces

One of our existing codes failed because a developer used Guid.TryParse to check if an input string is a valid Guid value and the input itself has a trailing space.

            if (Guid.TryParseExact("0c652e2a-ef02-4eff-8855-78122d8b6c0b ", "D", out var guid1))
                _logger.LogWarning("guid1");
            if (Guid.TryParse("0c652e2a-ef02-4eff-8855-78122d8b6c0b ", out var guid2))
                _logger.LogWarning("guid2");
            if (Guid.TryParse(" 0c652e2a-ef02-4eff-8855-78122d8b6c0b ", out var guid3))
                _logger.LogWarning("guid3");
            if (int.TryParse(" 1", out int int1))
                _logger.LogWarning("int1");

The output is

enter image description here

Anyone knows why is this? I would argue "0c652e2a-ef02-4eff-8855-78122d8b6c0b " is not a valid Guid because it has a trailing space. The same argument can be made "0c652e2a-ef02-4eff-8855-78122d8b6c0 b" is also not a valid GUID.

It seems like Microsoft library tries to be smart and trim trailing/leading spaces ….

>Solution :

According to the documentation, that’s how it was designed…no "Why" given.

This method is like the Parse method, except that instead of returning
the parsed GUID, it returns false if input is null or not in a
recognized format, and doesn’t throw an exception. It trims any
leading or trailing white space from input and converts strings in any
of the five formats recognized by the ToString(String) and
ToString(String, IFormatProvider) methods, as shown in the following
table.

(Emphasis mine)

If you’d like to get around that, you could always replace spaces with some illegal character.

Here’s a snippet of the actual code running (from decompilation). You’ll notice there’s no flag you can set to avoid it.

private static bool TryParseGuid(string g, GuidStyles flags, ref GuidResult result)
{
  if (g == null)
  {
    result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
    return false;
  }

  string text = g.Trim();
...

Leave a Reply