Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading