Is there a better way to generate 3 digit random number than the following:
var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
string my3digitrandomnumber = now.Substring(now.Length - 7, 3);
Thanks..
You should use this to get a number of 3 digits (less than 1000). Random rand = new Random(); // <-- Make this static somewhere const int maxValue = 999; string number = rand. Next(maxValue + 1). ToString("D3");
Description. The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
Yes - your current code isn't random at all. It's based on the system time. In particular, if you use this from several threads at the same time - or even several times within the same thread in quick succession - you'll get the same number each time.
You should be using Random
or RandomNumberGenerator
(which is more secure).
For example, once you've got an instance of Random
, you could use:
int value = rng.Next(1000);
string text = value.ToString("000");
(That's assuming you want the digits as text. If you want an integer which is guaranteed to be three digits, use rng.Next(100, 1000)
.)
However, there are caveats around Random
:
So ideally you probably want one per thread. My article on randomness talks more about this and gives some sample code.
int r = (new Random()).Next(100, 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With