Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Function In C#

Tags:

function

c#

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

like image 434
Amra Avatar asked Dec 01 '25 08:12

Amra


1 Answers

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)

like image 197
Øyvind Bråthen Avatar answered Dec 04 '25 00:12

Øyvind Bråthen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!