Possible Duplicate:
Random number generator not working the way I had planned (C#)
I have made a simple routine which generates a random number
private int randomNumber()
{
Random random = new Random();
int randomNum = random.Next(0, 100);
Response.Write(randomNum);
return randomNum;
}
I call this at two different stages throughout my page_load in the same way:
// A/B Test
if (randomNumber() <= 50)
{
...
I'm finding though, that both numbers are always the same. Any ideas?
When you create a Random
instance it's seeded with the current time. So if you create several of them at the same time they'll generate the same random number sequence. You need to create a single instance of Random
and use that.
new Random()
is initialized with current time as a seed. If you call it fast enough, then the seed will be the same and so is the result of Next()
call.
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