December 25th, 2024

How can I check if two GUIDs are equal when they are provided as strings?

A customer asked if there was a helper function in the system that accepted two strings and reported whether the GUIDs 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,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}} supported by 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 GUIDs. 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 GUIDs are passed as GUIDs.¹

¹ 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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.