5

I need to garuntee the uniqueness of an ID. Even if there's a 1 in 1 trillion chance of there being a dupe, I cannot use it.

But I don't really feel like going to the ends of the earth to find a solution either. I have spent some time looking into this, and everything I have found to date isn't able to garuntee me a unique ID.

So I thought I would use something very simple, like this:

    public static string GenerateItemID()
    {
        string year = DateTime.Now.Year.ToString(), 
            month = DateTime.Now.Month.ToString(), 
            day = DateTime.Now.Day.ToString(), 
            hour = DateTime.Now.Hour.ToString(), 
            minute = DateTime.Now.Minute.ToString(), 
            second = DateTime.Now.Second.ToString(), 
            millisecond = DateTime.Now.Millisecond.ToString();

        return year + month + day + hour + minute + second + millisecond;
    }

My logic here is: each new UI that is generated can not possibly be the same as any of the previous ones. But then I wondered if it were possible for a PC to generate two or more of these ID's within the same millisecond? Naturally, I then looked in Intellisense for a Nanosecond property, but it doesn't exist.

How can I generate an ID that is garunteed to be unique?

SE13013
  • 343
  • 3
  • 14

2 Answers2

4
var id = Guid.NewGuid(); 

I believe this will create a fairly unique id.

George Harnwell
  • 784
  • 2
  • 9
  • 19
  • Are GUID's _garunteed_ to _always_ be unique? I have read that there is still some margin for duplication. – SE13013 Jul 05 '15 at 14:23
  • I imagine there is 1 in a quadrillion chance or so. You could use a 'while' and say while (id is not unique) generate new guid? – George Harnwell Jul 05 '15 at 14:24
  • 1
    Guids will most likely be sufficient, check out this article for additional information: http://blogs.msdn.com/b/oldnewthing/archive/2008/06/27/8659071.aspx – Saragis Jul 05 '15 at 14:24
  • You could just add a random 8 digit number after your milliseconds. http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c – TRose Jul 05 '15 at 14:25
  • Then add logic to retry to generate a new GUID should the one you try to insert fail... – Azmi Kamis Jul 05 '15 at 14:26
  • @TRose I was just thinking that! lol – SE13013 Jul 05 '15 at 14:26
  • @SE13013 added a link to an example. – TRose Jul 05 '15 at 14:27
  • @SE13013 No, they aren't (see http://stackoverflow.com/a/30919505/613130)... But they are guaranteed to be statistically unique (in the sense that the probability of a collision is so much low to be *truly* low...) – xanatos Jul 05 '15 at 14:28
2

Let use GUID.

Refer here: https://msdn.microsoft.com/en-us/library/system.guid.newguid(v=vs.110).aspx

Hope this help.

hungndv
  • 2,121
  • 2
  • 19
  • 20