Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate Guid in .net

Tags:

c#

Please tell me how to validate GUID in .net and it is unique for always?

like image 576
AjmeraInfo Avatar asked Mar 03 '10 11:03

AjmeraInfo


People also ask

How do you validate a GUID?

If you are targeting a GUID in hex form, you can check that the string is 32-characters long (after stripping dashes and curly brackets) and has only letters A-F and numbers. from http://www.geekzilla.co.uk/view8AD536EF-BC0D-427F-9F15-3A1BC663848E.htm.

Is GUID in C#?

NET Framework using C# We can generate GUID by calling following code snippet. As you can see from this code, we use Guid. NewGuid() method to generate a new GUID in C#.

What is a valid GUID format?

The valid GUID (Globally Unique Identifier) must specify the following conditions: It should be a 128-bit number. It should be 36 characters (32 hexadecimal characters and 4 hyphens) long. It should be displayed in five groups separated by hyphens (-). Microsoft GUIDs are sometimes represented with surrounding braces.

What is the default value of GUID in C#?

default Guid is {00000000-0000-0000-0000-000000000000} . It's basically binary zeroes.


2 Answers

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!

like image 168
Hans Passant Avatar answered Oct 13 '22 01:10

Hans Passant


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;
}
like image 38
Kyle Rosendo Avatar answered Oct 13 '22 01:10

Kyle Rosendo