-1

I have a question concerning the Guid as a method to generate IDs. I need to be able to generate a new unique ID for each instance of a given class (I expect there to be a couple of hundreds of instances). I am including my code below:

class Program
{
    static void Main(string[] args)
    {
        Instance instance1 = new Instance();
        Console.WriteLine(instance1.ID);
        Instance instance2 = new Instance();
        Console.WriteLine(instance2.ID);
        Console.ReadKey();
    }
}
public static class GenerateID
{
    public static string NewID()
    {
        Guid guid = Guid.NewGuid();
        string id = guid.ToString();
        return id;
    }
}
public class Instance
{
    public string ID = GenerateID.NewID();
}

From what I can see, this method works, and two unique IDs are generated each time when I run the code, but I am not able to test this extensively, since I read that Guid is able to generate like a badgilion of IDs.

Would the way I implemented the above ensure that the ID's are unique each time? Or is there any chance of a collision? If so, what would be a better way to go about assigning unique IDs to instances?

EDIT: Alright, so I learned from ppl's answers that Guid is not inherently 100% unique (thanks, I'll make sure to read up on that), but my question is whether the method I used to get the ID may heighten the chance that the same two IDs will be generated? Or is this a good way to go about obtaining unique IDs?

guy120334913
  • 43
  • 1
  • 6
  • 1
    This silliness about GUID collisions is very unproductive. The real problem is that you are not considering the cheap solution. Getting a new id is trivial, one more than the previous one is good enough. 4 billion is already a huge number but use a *long* to store it and you can't get a duplicate in 194 years no matter how hard you try. Whether you need to use `++` or Interlocked.Increment() to make it thread-safe is up to you. – Hans Passant May 15 '16 at 12:32

2 Answers2

3

Guid.NewGuid() is, using MSDN's words, "very high degree of certainty", unique.

The .NET call calls WIN32's CoCreateGuid() (which calls UuidCreate) whose remarks are set out below:

MSDN:

To a very high degree of certainty, this function returns a unique value – no other invocation, on the same or any other system (networked or not), should return the same value - Golly, tell me more

0

Each GUID you generate contains sequence of 32 hex digits which made by 2^128 numbers! So the chance to get duplicate GUIDs is almost zero. Considering GUIDs made of 128-bit random numbers, makes possibility of making duplicate GUIDs to zero, even if you generate them at same time

Saeed K
  • 13
  • 6