In the application, when special types of objects are created, I need to generate a unique-id for each of them. The objects are created thro’ a factory and have a high possibility of being created in a ‘bulk’ operation. I realize that the ‘Random’ from the framework is not so ‘random’ after all, so I tried appending the time-stamp as follows:
private string GenerateUniqueId() { Random randomValue = new Random(); return DateTime.Now.Ticks.ToString() + randomValue.Next().ToString(); }
Unfortunately, even this does not work. For objects that are created in rapid succession, I generate the same Unique Id 🙁
Currently, I am implementing it in a crude way as follows:
private string GenerateUniqueId() { Random randomValue = new Random(); int value = randomValue.Next(); Debug.WriteLine(value.ToString()); Thread.Sleep(100); return DateTime.Now.Ticks.ToString() + value.ToString(); }
Since this is not a very large application, I think a simple and quick technique would suffice instead of implementing an elaborate algorithm.
Please suggest.
A GUID is probably what you’re looking for:
If you want a smaller, more manageable ID then you could use something like this:
Note: This will only give you a 64-bit number in comparison to the GUID’s 128 bits, so there’ll be more chance of a collision. Probably not an issue in the real world though. If it is an issue then you could increase the size of the
bytearray to generate a larger id.