What is the best way to select a random number between two numbers in C#?
For instance, if I have a low value of 23 and a high value of 9999, what would the correct code be to select a random number between and including these two numbers? Thanks in Advance
Use the Random class like this:
Random rnd = new Random();
rnd.Next(23, 10000);
Make sure that you only initialize your rnd object once, to make sure it really generate random values for you.
If you make this loop for instance:
for( int i = 0 ; i < 10; i++ ){
Random rnd = new Random();
var temp = rnd.Next(23, 10000);
}
temp will be the same each time, since the same seed is used to generate the rnd object, but like this:
Random rnd = new Random();
for( int i = 0 ; i < 10; i++ ){
var temp = rnd.Next(23, 10000);
}
It will generate 10 unique random numbers (but of course, by chance, two or more numbers might be equal anyway)
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