I am using this code to generate a 8 digit unique number.
byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToUInt32(buffer, 8).ToString();
<
Any random sequence is bound to have some collisions. It's just a matter of when. Using the birthday paradox formula, with 100,000,000 possible values (8 digits), the chance that you will have a collision with only 10,000 elements is around 40% and 99% with 30,000 elements. (see here for a calculator).
If you really need a random sequence, you should not use a GUID for this purpose. GUIDs have very specific structure and should only be taken as a whole. It is easy enough to create a random 8 digit sequence generator. This should give you an 8 digit sequence:
public string Get8Digits()
{
var bytes = new byte[4];
var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
uint random = BitConverter.ToUInt32(bytes, 0) % 100000000;
return String.Format("{0:D8}", random);
}
You can also take the RandomNumberGenerator and place it somewhere to avoid creating a new one everytime.
My first answer did not address the uniqueness problem. My second one does:
static int counter;
public static int GetUniqueNumber()
{
return counter++;
}
If you want to have unique numbers across app restarts, you need to persist the value of counter to a database or somewhere else after each and every GetUniqueNumber call.
This method will generate a random string, it doesn't rely on the Random method and also is far better than the guid approch :
public static string gen_Digits(int length)
{
var rndDigits = new System.Text.StringBuilder().Insert(0, "0123456789", length).ToString().ToCharArray();
return string.Join("", rndDigits.OrderBy(o => Guid.NewGuid()).Take(length));
}
you can increase the length for less collision chance, but to have a 100% unique sequence you have to persist the old generated values and check the newly created value for uniquness.