jump to navigation

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

Posted by codinglifestyle in C#.
Tags: , , ,

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;


No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: