how can i generate 16 digit unique random numbers without any repetition in c# asp.net, as i have read the concept of GUID which generate characters along with numbers but i don’t want characters
kindly suggest is there any way to acheive it
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can create a random number using the Random class:
private static Random RNG = new Random();
public string Create16DigitString()
{
var builder = new StringBuilder();
while (builder.Length < 16)
{
builder.Append(RNG.Next(10).ToString());
}
return builder.ToString();
}
Ensuring that there are no collisions requires you to track all results that you have previously returned, which is in effect a memory leak (NB I do not recommend that you use this – keeping track of all previous results is a bad idea, rely on the entropy of a random string of up to 16 characters, if you want more uniqueness, increase the entropy, but I shall include it to show how it could be done):
private static HashSet<string> Results = new HashSet<string>();
public string CreateUnique16DigitString()
{
var result = Create16DigitString();
while (!Results.Add(result))
{
result = Create16DigitString();
}
return result;
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0