jump to navigation

The correct way to test if a string is a Guid May 25, 2006

Posted by codinglifestyle in C#.
Tags: , , ,
add a comment

Recently I’ve had a few scenarios where I needed to test if a string was a guid.  I had a dirty solution using a try/catch but today I needed to perform this test thousands of times and this was much too slow.  So a quick search turned up this beauty and shows the “right” way to perform this test.

 using System.Text.RegularExpressions;
   
 private static Regex isGuid = new Regex(@”^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$”, RegexOptions.Compiled);
    internal static bool IsGuid(string candidate, out Guid output)
    {
        bool isValid = false;
        output = Guid.Empty;

        if (candidate != null)
        {
            if (isGuid.IsMatch(candidate))
            {
                output = new Guid(candidate);
                isValid = true;
            }
        }
        return isValid;
    }