Amra
Amra

Reputation: 211

Random Function In 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

Upvotes: 2

Views: 21290

Answers (2)

Mark Byers
Mark Byers

Reputation: 837916

It depends on whether you are looking for an integer or a double. For an integer use Random.Next(minValue, maxValue):

Returns a random number within a specified range.

Note that the minValue is inclusive but the maxValue is exclusive.

There is no equivalent method for choosing a random double within a specified range. Instead you should use the NextDouble method to pick a random number between 0.0 and 1.0 and then use a linear transformation to extend, reduce and/or translate the range.

Upvotes: 7

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60684

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)

Upvotes: 13

Related Questions