How to validate Guid in .net

Guid's are unique 99.99999999999999999999999999999999% of the time.

It depends on what you mean by validate?

Code to determine that a Guid string is in fact a Guid, is as follows:

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;
}

Here's a non-Regex answer that should be pretty fast:

public static bool IsHex(this char c)
{
    return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
}

public static bool IsGuid(this string s)
{
    // Length of a proper GUID, without any surrounding braces.
    const int len_without_braces = 36;

    // Delimiter for GUID data parts.
    const char delim = '-';

    // Delimiter positions.
    const int d_0 = 8;
    const int d_1 = 13;
    const int d_2 = 18;
    const int d_3 = 23;

    // Before Delimiter positions.
    const int bd_0 = 7;
    const int bd_1 = 12;
    const int bd_2 = 17;
    const int bd_3 = 22;

    if (s == null)
        return false;

    if (s.Length != len_without_braces)
        return false;

    if (s[d_0] != delim ||
        s[d_1] != delim ||
        s[d_2] != delim ||
        s[d_3] != delim)
        return false;

    for (int i = 0;
        i < s.Length;
        i = i + (i == bd_0 ||
                i == bd_1 ||
                i == bd_2 ||
                i == bd_3
                ? 2 : 1))
    {
        if (!IsHex(s[i])) return false;
    }

    return true;
}

You cannot validate GUID's uniqueness. You just hope it was generated with a tool that produces unique 16 bytes. As for validation, this simple code might work (assuming you are dealing with GUID's string representation:

bool ValidateGuid(string theGuid)
{
  try { Guid aG = new Guid(theGuid); }
  catch { return false; }

  return true;
}

2^128 is a very, very large number. It is a billion times larger than the number of picoseconds in the life of the universe. Too large by a long shot to ever validate, the answer is doomed to be "42". Which is the point of using them: you don't have to. If you worry about getting duplicates then you worry for the wrong reason. The odds your machine will be destroyed by a meteor impact are considerably larger.

Duck!

Tags:

C#