Random Function In C#
Solution 1
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)
Solution 2
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.
Amra
Updated on August 03, 2022Comments
-
Amra over 1 year
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
-
Amra over 13 yearsAre you sure ? i write this code in VS but there is no sub like 'Next' in Random Function . Tnx for your helping
-
Mark Byers over 13 years@Eva: It's an instance method - you need a Random object (for example you can create one when your program starts).
-
Øyvind Bråthen over 13 years@Eva - There is no static Next function if that is what you are trying to do, so you can't simply write Random.Next. See my answer for details.
-
Amra over 13 yearsThanks . If i want select a random string from a Text file , what am i going to do ?
-
Mark Byers over 13 years@Eva: There are also some examples on the page I linked to. Have you looked at those?
-
Jon Skeet over 13 years@Eva: The simplest way would be to read all the lines from the text file, remembering them all and counting them, then select a random number based on the count.
-
Amra over 13 yearsYes I see Them . Thanks . Nice Example ;)
-
codeulike over 13 yearsYour example makes it look like a static method because of the capital R on Random. Its a little confusing.
-
Darth Coder almost 10 years@Knobloch: Can you explain why the seed remains the same in the first case and changes in the second condition? Doesn't the loop create a new instance for 'rnd' for iteration of the loop?