A customer asked if there was a helper function in the system that accepted two strings and reported whether the GUID
s they represent are equal.
This is a tricky question, because you first have to decide what “represent” means.
There are many ways of representing a GUID
as a string. It could be just 32 case-insensitive hexadecimal digits. Or maybe there are internal hyphens to separate the groups. And the whole thing might be enclosed in braces or parentheses. External and interior whitespace might be allowed. Trailing garbage might be accepted (and ignored). And then there’s the special format {0x00000000,System.Guid.Parse
. That last one is tricky because it means you can’t just use a naïve algorithm of just discarding anything that is not a hexadecimal digit.
The simplest solution is to pass both strings to a GUID
parser that supports the formats that you want to support, then compare the resulting GUID
s. You could write something fancy (say, ignore anything that’s not a hexadecimal digit, or the sequence 0x), but the straightforwardness of just deferring to another parser likely outweighs the risk that your custom GUID
comparison function will mess something up.
If comparing GUID
-holding strings is a bottleneck in your code, then the solution is not to improve your “comparing two GUID
-holding strings” function, but rather to change your code so that GUID
s are passed as GUID
s.¹
¹ If the string arrives from an external source (say, JSON), then convert it to a GUID
immediately upon parsing the JSON, and then use the parsed value from then on.
0 comments