Search code examples
c#numbersunique

How to Generate Unique Number of 8 digits?


I am using this code to generate a 8 digit unique number.

byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToUInt32(buffer, 8).ToString();

Does this code really generate a unique number or might it repeat the same number again?


Solution

  • A GUID is not just a random number; it's composed of segments. Some of the segments will not change at all if the guid is generated on the same computer. By using only 64-bits of the original 128-bits you are breaking the structure of the guid and most likely breaking the uniqueness of the generated number.

    This question has more info on uniqueness of guids, check this link as well for more info on why it's bad to use only part of a guid if you need a unique number.

    If you need to limit duplication to an absolute minimum, an incremental counter will give you what you need. If your application is using multiple threads or processes, a counter may be hard (or even impossible) to implement correctly.

    This is the realm that guids were designed for, to be unique across multiple machines. So if uniqueness across machines is a requirement you should use guids. The whole guid.